home *** CD-ROM | disk | FTP | other *** search
/ CD BIT 75 / CD BIT 75.iso / Software / SinfoSeguros / MSDE / Setup / SqlRun.cab / procsyst.sql.24170C3F_A9E4_47C1_8DFE_FD79C2714697 < prev    next >
Encoding:
Text File  |  2002-12-11  |  537.1 KB  |  19,807 lines

  1. /*
  2. ** ProcSyst.SQL
  3. ** Copyright Microsoft, Inc. 1994 - 2000
  4. ** All Rights Reserved.
  5. */
  6.  
  7. go
  8. use master
  9. go
  10. checkpoint
  11. go
  12. set nocount on
  13. set implicit_transactions off
  14. set ansi_nulls off
  15. set quoted_identifier on    -- Force all ye devs to do this correctly!
  16. go
  17.  
  18. declare @vdt varchar(99)
  19. select  @vdt = convert(varchar,getdate(),113)
  20. raiserror('Starting Install\ProcSyst.SQL at  %s',0,1,@vdt) with nowait
  21. go
  22.  
  23. print ' '
  24. print 'Making sure that updates to system tables are allowed.'
  25. go
  26.  
  27. declare  @int1            integer
  28. --dbcc getvalue('current_version')  --1=4.21A ,400-406=6.0 ,407-?=6.5, currently 408=7.0
  29. --select @dbcc_current_version = @@error
  30.  
  31. if (     object_id('sp_configure','P') IS NOT NULL
  32.     AND  1 <> (select value from syscurconfigs where config = 102)
  33.    )
  34.     begin                        --Query tree compatible
  35.     exec @int1 = sp_configure 'allow updates',1
  36.     if @@error <> 0 or @int1 <> 0
  37.         raiserror('Bad sp_configure exec at top of ProcSyst.SQL, killing spid.'
  38.             ,22,127) with log
  39.     reconfigure with override
  40.     end
  41. go
  42.  
  43. ---- Make sure server was started in single user mode or that sp_configure was used
  44. ----    to enable updates to system tables.
  45.  
  46. if (select value from syscurconfigs where config = 102) <> 1
  47.     raiserror('Cannot run ProcSyst.SQL unless updates to system tables are enabled.  Shutdown server and restart with the ''-m'' option or use sp_configure to enable updates to system tables.'
  48.             ,22,127) with log
  49. go
  50.  
  51. exec sp_MS_upd_sysobj_category 1  --Capture now_datetime for use below.
  52.  
  53. go
  54.  
  55. print ' '
  56. print 'Dropping procedures that will be (re)created.'
  57. go
  58.  
  59. ----- ---
  60.  
  61. if object_id('sp_fallback_activate_svr','P') IS NOT NULL
  62.     drop procedure sp_fallback_activate_svr
  63. if object_id('sp_fallback_activate_svr_db','P') IS NOT NULL
  64.     drop procedure sp_fallback_activate_svr_db
  65.  
  66. if object_id('sp_fallback_deactivate_svr','P') IS NOT NULL
  67.     drop procedure sp_fallback_deactivate_svr
  68. if object_id('sp_fallback_deactivate_svr_db','P') IS NOT NULL
  69.     drop procedure sp_fallback_deactivate_svr_db
  70.  
  71. if object_id('sp_fallback_enroll_svr_db','P') IS NOT NULL
  72.     drop procedure sp_fallback_enroll_svr_db
  73.  
  74. if object_id('sp_fallback_help','P') IS NOT NULL
  75.     drop procedure sp_fallback_help
  76.  
  77. if object_id('sp_fallback_help_db_dev','P') IS NOT NULL
  78.     drop procedure sp_fallback_help_db_dev
  79.  
  80. if object_id('sp_fallback_MS_enroll_db','P') IS NOT NULL
  81.     drop procedure sp_fallback_MS_enroll_db
  82.  
  83. if object_id('sp_fallback_MS_enroll_dev','P') IS NOT NULL
  84.     drop procedure sp_fallback_MS_enroll_dev
  85.  
  86. if object_id('sp_fallback_MS_enroll_usg','P') IS NOT NULL
  87.     drop procedure sp_fallback_MS_enroll_usg
  88.  
  89. if object_id('sp_fallback_MS_sel_fb_svr','P') IS NOT NULL
  90.     drop procedure sp_fallback_MS_sel_fb_svr
  91.  
  92. if object_id('sp_fallback_MS_verify_ri','P') IS NOT NULL
  93.     drop procedure sp_fallback_MS_verify_ri
  94.  
  95. if object_id('sp_fallback_permanent_svr','P') IS NOT NULL
  96.     drop procedure sp_fallback_permanent_svr
  97.  
  98. if object_id('sp_fallback_upd_dev_drive','P') IS NOT NULL
  99.     drop procedure sp_fallback_upd_dev_drive
  100.  
  101. if object_id('sp_fallback_withdraw_svr_db','P') IS NOT NULL
  102.     drop procedure sp_fallback_withdraw_svr_db
  103.  
  104.  
  105. go
  106. ------------------------------------------------------------
  107.  
  108. if object_id('sp_a_count_bits_on','P') IS NOT NULL
  109.              drop procedure sp_a_count_bits_on
  110.  
  111. if object_id('sp_addextendedproc','P') IS NOT NULL
  112.     drop procedure sp_addextendedproc
  113.  
  114. if object_id('sp_addmessage','P') IS NOT NULL
  115.     drop procedure sp_addmessage
  116.  
  117. if object_id('sp_addremotelogin','P') IS NOT NULL
  118.     drop procedure sp_addremotelogin
  119.  
  120. if object_id('sp_addsegment','P') IS NOT NULL
  121.     drop procedure sp_addsegment
  122. go
  123.  
  124. checkpoint
  125. go
  126.  
  127. if object_id('sp_addtype','P') IS NOT NULL
  128.     drop procedure sp_addtype
  129.  
  130. if object_id('sp_addumpdevice','P') IS NOT NULL
  131.     drop procedure sp_addumpdevice
  132.  
  133. if object_id('sp_altermessage','P') IS NOT NULL
  134.         drop procedure sp_altermessage
  135.  
  136. if object_id('sp_attach_db','P') IS NOT NULL
  137.     drop procedure sp_attach_db
  138.  
  139. if object_id('sp_attach_single_file_db','P') IS NOT NULL
  140.     drop procedure sp_attach_single_file_db
  141. go
  142.  
  143. if object_id('sp_bindefault','P') IS NOT NULL
  144.     drop procedure sp_bindefault
  145.  
  146. if object_id('sp_bindrule','P') IS NOT NULL
  147.     drop procedure sp_bindrule
  148.  
  149. if object_id('sp_blockcnt','P') IS NOT NULL
  150.     drop procedure sp_blockcnt
  151.  
  152. if object_id('sp_checknames','P') IS NOT NULL
  153.     drop procedure sp_checknames
  154. go
  155.  
  156. if object_id('sp_configure','P') IS NOT NULL
  157.     drop procedure sp_configure
  158.  
  159. if object_id('sp_create_removable','P') IS NOT NULL
  160.     drop procedure sp_create_removable
  161.  
  162. if object_id('sp_createstats','P') IS NOT NULL
  163.     drop procedure sp_createstats
  164.  
  165. if object_id('sp_cycle_errorlog','P') IS NOT NULL
  166.     drop procedure sp_cycle_errorlog
  167.  
  168. if object_id('sp_certify_removable','P') IS NOT NULL
  169.     drop procedure sp_certify_removable
  170.  
  171. if object_id('sp_check_removable','P') IS NOT NULL
  172.     drop procedure sp_check_removable
  173.  
  174. if object_id('sp_cnst_csr','P') IS NOT NULL
  175.     drop procedure sp_cnst_csr
  176.  
  177. if object_id('sp_coalesce_fragments','P') IS NOT NULL
  178.     drop procedure sp_coalesce_fragments
  179.  
  180. if object_id('sp_dboption','P') IS NOT NULL
  181.     drop procedure sp_dboption
  182.  
  183. if object_id('sp_dbcmptlevel','P') IS NOT NULL
  184.     drop procedure sp_dbcmptlevel
  185.  
  186. if object_id('sp_dbremove','P') IS NOT NULL
  187.     drop procedure sp_dbremove
  188.  
  189. if object_id('sp_depends','P') IS NOT NULL
  190.     drop procedure sp_depends
  191.  
  192. if object_id('sp_detach_db','P') IS NOT NULL
  193.     drop procedure sp_detach_db
  194.  
  195. if object_id('sp_diskdefault','P') IS NOT NULL
  196.     drop procedure sp_diskdefault
  197. go
  198.  
  199. if object_id('sp_dropdevice','P') IS NOT NULL
  200.     drop procedure sp_dropdevice
  201.  
  202. if object_id('sp_dropdumpdevice','P') IS NOT NULL
  203.     drop procedure sp_dropdumpdevice
  204.  
  205. if object_id('sp_dropextendedproc','P') IS NOT NULL
  206.     drop procedure sp_dropextendedproc
  207. go
  208.  
  209. if object_id('sp_dropmessage','P') IS NOT NULL
  210.     drop procedure sp_dropmessage
  211.  
  212. if object_id('sp_droptype','P') IS NOT NULL
  213.     drop procedure sp_droptype
  214.  
  215. if object_id('sp_dropremotelogin','P') IS NOT NULL
  216.     drop procedure sp_dropremotelogin
  217.  
  218. if object_id('sp_dropsegment','P') IS NOT NULL
  219.     drop procedure sp_dropsegment
  220.  
  221. if object_id('sp_extendsegment','P') IS NOT NULL
  222.     drop procedure sp_extendsegment
  223. go
  224.  
  225. if object_id('sp_help','P') IS NOT NULL
  226.     drop procedure sp_help
  227.  
  228. if object_id('sp_help_revdatabase','P') IS NOT NULL
  229.              drop procedure sp_help_revdatabase
  230.  
  231. if object_id('sp_helpconstraint','P') IS NOT NULL
  232.     drop procedure sp_helpconstraint
  233.  
  234. if object_id('sp_helpdb','P') IS NOT NULL
  235.     drop procedure sp_helpdb
  236.  
  237. if object_id('sp_helpdevice','P') IS NOT NULL
  238.     drop procedure sp_helpdevice
  239.  
  240. if object_id('sp_helpextendedproc','P') IS NOT NULL
  241.     drop procedure sp_helpextendedproc
  242.  
  243. if object_id('sp_helpfile','P') IS NOT NULL
  244.     drop procedure sp_helpfile
  245.  
  246. if object_id('sp_helpfilegroup','P') IS NOT NULL
  247.     drop procedure sp_helpfilegroup
  248.  
  249. if object_id('sp_helpgroup','P') IS NOT NULL
  250.     drop procedure sp_helpgroup
  251.  
  252. if object_id('sp_helpindex','P') IS NOT NULL
  253.     drop procedure sp_helpindex
  254.  
  255. if object_id('sp_helpstats','P') IS NOT NULL
  256.     drop procedure sp_helpstats
  257. go
  258.  
  259. if exists (select * from sysobjects
  260.        where xtype = N'IF' and uid = USER_ID('system_function_schema') and
  261.         name = 'fn_dblog')
  262.     drop function system_function_schema.fn_dblog
  263. go
  264.  
  265. if exists (select * from sysobjects
  266.        where xtype = N'TF' and uid = USER_ID('system_function_schema') and
  267.         name = 'fn_helpcollations')
  268.     drop function system_function_schema.fn_helpcollations
  269. go
  270.  
  271. if exists (select * from sysobjects
  272.        where xtype = N'TF' and uid = USER_ID('system_function_schema') and
  273.         name = 'fn_trace_getinfo')
  274.     drop function system_function_schema.fn_trace_getinfo
  275. go
  276.  
  277. if exists (select * from sysobjects
  278.        where xtype = N'IF' and uid = USER_ID('system_function_schema') and
  279.         name = 'fn_trace_gettable')
  280.     drop function system_function_schema.fn_trace_gettable
  281. go
  282.  
  283. if exists (select * from sysobjects
  284.        where xtype = N'TF' and uid = USER_ID('system_function_schema') and
  285.         name = 'fn_trace_geteventinfo')
  286.     drop function system_function_schema.fn_trace_geteventinfo
  287. go
  288.  
  289. if exists (select * from sysobjects
  290.        where xtype = N'TF' and uid = USER_ID('system_function_schema') and
  291.         name = 'fn_trace_getfilterinfo')
  292.     drop function system_function_schema.fn_trace_getfilterinfo
  293. go
  294.  
  295. if exists (select * from sysobjects
  296.        where xtype = N'TF' and uid = USER_ID('system_function_schema') and
  297.         name = 'fn_databaseproperties')
  298.     drop function system_function_schema.fn_databaseproperties
  299. go
  300.  
  301. if exists (select * from sysobjects
  302.        where xtype = N'TF' and uid = USER_ID('system_function_schema') and
  303.         name = 'fn_servershareddrives')
  304.     drop function system_function_schema.fn_servershareddrives
  305. go
  306.  
  307. if exists (select * from sysobjects
  308.        where xtype = N'TF' and uid = USER_ID('system_function_schema') and
  309.         name = 'fn_virtualfilestats')
  310.     drop function system_function_schema.fn_virtualfilestats
  311. go
  312.  
  313. if exists (select * from sysobjects
  314.        where xtype = N'TF' and uid = USER_ID('system_function_schema') and
  315.         name = 'fn_virtualservernodes')
  316.     drop function system_function_schema.fn_virtualservernodes
  317. go
  318.  
  319. if exists (select * from sysobjects
  320.        where xtype = N'TF' and uid = USER_ID('system_function_schema') and
  321.         name = 'fn_get_sql')
  322.     drop function system_function_schema.fn_get_sql
  323. go
  324.  
  325. checkpoint
  326. go
  327.  
  328. if object_id('sp_helplanguage','P') IS NOT NULL
  329.     drop procedure sp_helplanguage
  330.  
  331. if object_id('sp_helplog','P') IS NOT NULL
  332.     drop procedure sp_helplog
  333.  
  334. if object_id('sp_helplogins','P') IS NOT NULL
  335.              drop procedure sp_helplogins
  336.  
  337. if object_id('sp_helprotect','P') IS NOT NULL
  338.     drop procedure sp_helprotect
  339.  
  340. if object_id('sp_helptext','P') IS NOT NULL
  341.     drop procedure sp_helptext
  342.  
  343. if object_id('sp_helpuser','P') IS NOT NULL
  344.     drop procedure sp_helpuser
  345.  
  346. if object_id('sp_helpremotelogin','P') IS NOT NULL
  347.     drop procedure sp_helpremotelogin
  348.  
  349. if object_id('sp_helpsegment','P') IS NOT NULL
  350.     drop procedure sp_helpsegment
  351.  
  352. if object_id('sp_helpsort','P') IS NOT NULL
  353.     drop procedure sp_helpsort
  354.  
  355. if object_id('sp_helpsql','P') IS NOT NULL
  356.     drop procedure sp_helpsql
  357.  
  358. if object_id('sp_indexoption','P') IS NOT NULL
  359.     drop procedure sp_indexoption
  360.  
  361. if object_id('sp_lock','P') IS NOT NULL
  362.     drop procedure sp_lock
  363.  
  364. if object_id('sp_getapplock','P') IS NOT NULL
  365.     drop procedure sp_getapplock
  366.  
  367. if object_id('sp_releaseapplock','P') IS NOT NULL
  368.     drop procedure sp_releaseapplock
  369. go
  370.  
  371. if object_id('sp_logdevice','P') IS NOT NULL
  372.     drop procedure sp_logdevice
  373.  
  374. if object_id('sp_monitor','P') IS NOT NULL
  375.     drop procedure sp_monitor
  376.  
  377. if object_id('sp_namecrack','P') IS NOT NULL
  378.     drop procedure sp_namecrack
  379.  
  380. if object_id('sp_namecrack_qi','P') IS NOT NULL
  381.     drop procedure sp_namecrack_qi
  382.  
  383. if object_id('sp_objectfilegroup','P') IS NOT NULL
  384.     drop procedure sp_objectfilegroup
  385.  
  386. if object_id('sp_placeobject','P') IS NOT NULL
  387.     drop procedure sp_placeobject
  388.  
  389. if object_id('sp_procoption','P') IS NOT NULL
  390.     drop procedure sp_procoption
  391.  
  392. if object_id('sp_processmail','P') IS NOT NULL
  393.     drop procedure sp_processmail
  394. go
  395.  
  396. if object_id('sp_recompile','P') IS NOT NULL
  397.     drop procedure sp_recompile
  398.  
  399. if object_id('sp_remoteoption','P') IS NOT NULL
  400.     drop procedure sp_remoteoption
  401.  
  402. if object_id('sp_rename','P') IS NOT NULL
  403.     drop procedure sp_rename
  404.  
  405. if object_id('sp_renamedb','P') IS NOT NULL
  406.     drop procedure sp_renamedb
  407.  
  408. if object_id('sp_remove_tempdb_file','P') IS NOT NULL
  409.         drop procedure sp_remove_tempdb_file
  410.  
  411. if object_id('sp_resetstatus','P') IS NOT NULL
  412.    drop procedure sp_resetstatus
  413. go
  414.  
  415. if object_id('sp_add_file_recover_suspect_db','P') IS NOT NULL
  416.     drop procedure sp_add_file_recover_suspect_db
  417.  
  418. if object_id('sp_add_data_file_recover_suspect_db','P') IS NOT NULL
  419.     drop procedure sp_add_data_file_recover_suspect_db
  420.  
  421. if object_id('sp_add_log_file_recover_suspect_db','P') IS NOT NULL
  422.     drop procedure sp_add_log_file_recover_suspect_db
  423. go
  424.  
  425. if object_id('sp_spaceused','P') IS NOT NULL
  426.     drop procedure sp_spaceused
  427.  
  428. if object_id('sp_checktabletempsize', 'P') IS NOT NULL
  429.     drop procedure sp_checktabletempsize
  430.  
  431. if object_id('sp_checkdbtempsize', 'P') IS NOT NULL
  432.     drop procedure sp_checkdbtempsize
  433.  
  434. if object_id('sp_sqlexec','P') IS NOT NULL
  435.     drop procedure sp_sqlexec
  436. go
  437.  
  438. if object_id('sp_tableoption','P') IS NOT NULL
  439.     drop procedure sp_tableoption
  440.  
  441. if object_id('sp_invalidate_textptr','P') IS NOT NULL
  442.     drop procedure sp_invalidate_textptr
  443.  
  444. if object_id('sp_tempdbspace','P') IS NOT NULL
  445.     drop procedure sp_tempdbspace
  446.  
  447. if object_id('sp_unbindefault','P') IS NOT NULL
  448.     drop procedure sp_unbindefault
  449.  
  450. if object_id('sp_unbindrule','P') IS NOT NULL
  451.     drop procedure sp_unbindrule
  452.  
  453.  
  454. if object_id('sp_user_counter1','P') IS NOT NULL
  455.         drop procedure sp_user_counter1
  456. if object_id('sp_user_counter2','P') IS NOT NULL
  457.         drop procedure sp_user_counter2
  458. if object_id('sp_user_counter3','P') IS NOT NULL
  459.         drop procedure sp_user_counter3
  460. if object_id('sp_user_counter4','P') IS NOT NULL
  461.         drop procedure sp_user_counter4
  462. if object_id('sp_user_counter5','P') IS NOT NULL
  463.         drop procedure sp_user_counter5
  464. if object_id('sp_user_counter6','P') IS NOT NULL
  465.         drop procedure sp_user_counter6
  466. if object_id('sp_user_counter7','P') IS NOT NULL
  467.         drop procedure sp_user_counter7
  468. if object_id('sp_user_counter8','P') IS NOT NULL
  469.         drop procedure sp_user_counter8
  470. if object_id('sp_user_counter9','P') IS NOT NULL
  471.         drop procedure sp_user_counter9
  472. if object_id('sp_user_counter10','P') IS NOT NULL
  473.         drop procedure sp_user_counter10
  474. go
  475.  
  476.  
  477. if object_id('sp_validaltlang','P') IS NOT NULL
  478.     drop procedure sp_validaltlang
  479.  
  480. if object_id('sp_validlang','P') IS NOT NULL
  481.     drop procedure sp_validlang
  482.  
  483. if object_id('sp_validname','P') IS NOT NULL
  484.     drop procedure sp_validname
  485.  
  486. if object_id('sp_who','P') IS NOT NULL
  487.     drop procedure sp_who
  488.  
  489. if object_id('sp_who2','P') IS NOT NULL
  490.     drop procedure sp_who2
  491. go
  492.  
  493. if object_id('sp_updatestats','P') IS NOT NULL
  494.     drop procedure sp_updatestats
  495. go
  496.  
  497. if object_id('sp_autostats','P') IS NOT NULL
  498.     drop procedure sp_autostats
  499. go
  500.  
  501. if object_id('sp_helptrigger','P') IS NOT NULL
  502.     drop procedure sp_helptrigger
  503. go
  504.  
  505. if object_id('sp_dropextendedproperty','P') IS NOT NULL
  506.     drop procedure sp_dropextendedproperty
  507. if object_id('sp_addextendedproperty','P') IS NOT NULL
  508.     drop procedure sp_addextendedproperty
  509. if object_id('sp_updateextendedproperty','P') IS NOT NULL
  510.     drop procedure sp_updateextendedproperty
  511. if object_id('sp_validatepropertyinputs','P') IS NOT NULL
  512.     drop procedure sp_validatepropertyinputs
  513. if exists (select * from sysobjects
  514.        where xtype = N'TF' and uid = USER_ID('system_function_schema') and
  515.         name = 'fn_listextendedproperty')
  516.     drop function system_function_schema.fn_listextendedproperty
  517. go
  518.  
  519. if object_id('sp_fixindex','P') IS NOT NULL
  520.     drop procedure sp_fixindex
  521. go
  522.  
  523. if object_id('MS_sqlctrs_users','P') IS NOT NULL
  524.     drop proc MS_sqlctrs_users
  525. go
  526.  
  527. checkpoint
  528. go
  529.  
  530.  
  531. -------------------------
  532.  -- create XP early for sysdepends
  533. raiserror('Special section to create extended procs early for sysdepends...',0,1)
  534. go
  535.  
  536.  
  537. raiserror(15339,-1,-1,'sp_dropextendedproc')
  538. go
  539. create procedure sp_dropextendedproc --- 1996/08/30 20:13
  540. @functname nvarchar(517) -- name of function
  541. as
  542. /*
  543. **  If we're in a transaction, disallow the dropping of the
  544. **  extended stored procedure.
  545. */
  546. set implicit_transactions off
  547. if @@trancount > 0
  548.     begin
  549.         raiserror(15002,-1,-1,'sp_dropextendedproc')
  550.         return (1)
  551.     end
  552.  
  553. /*
  554. ** Drop the extended procedure mapping.
  555. */
  556. dbcc dropextendedproc( @functname )
  557. return (0) -- sp_dropextendedproc
  558. go
  559.  
  560.  
  561.  
  562. raiserror(15339,-1,-1,'sp_addextendedproc')
  563. go
  564. create procedure sp_addextendedproc --- 1996/08/30 20:13
  565. @functname nvarchar(517),        /* (owner.)name of function to call */
  566. @dllname varchar(255)        /* name of DLL containing function */
  567. as
  568. /*
  569. **  If we're in a transaction, disallow the addition of the
  570. **  extended stored procedure.
  571. */
  572. set implicit_transactions off
  573. if @@trancount > 0
  574. begin
  575.     raiserror(15002,-1,-1,'sp_addextendedproc')
  576.     return (1)
  577. end
  578.  
  579. -- Disallow 0-length string & NULL
  580. if @dllname is null or datalength(@dllname) = 0
  581. begin
  582.     raiserror(15311,-1,-1,@dllname)
  583.     return (1)
  584. end
  585.  
  586. /*
  587. ** Create the extended procedure mapping.
  588. */
  589. dbcc addextendedproc( @functname, @dllname)
  590. return (0) -- sp_addextendedproc
  591. go
  592.  
  593.  
  594. raiserror(15339,-1,-1,'sp_helpextendedproc')
  595. go
  596. create procedure sp_helpextendedproc --- 1996/08/14 15:53
  597. @funcname sysname = NULL
  598. as
  599.  
  600. set nocount on
  601.  
  602. if (select count(*) from master.dbo.sysobjects where xtype = N'X ') = 0
  603.     begin
  604.         raiserror(15326,-1,-1)
  605.         return (0)
  606.     end
  607.  
  608.  
  609. if @funcname is not null
  610. begin
  611.     /*
  612.     **  Make sure the function name exists
  613.     */
  614.     if not exists (select * from master.dbo.sysobjects
  615.             where xtype = N'X '
  616.               and name = @funcname)
  617.     begin
  618.         raiserror(15019,-1,-1,@funcname)
  619.         return (1)
  620.     end
  621.     /*print out select function name info*/
  622.     select distinct name = o.name, dll = substring(c.text,1,255)
  623.     from master.dbo.sysobjects o, master.dbo.syscomments c
  624.     where o.id = c.id
  625.         and o.name = @funcname
  626.         and o.xtype = N'X '
  627.     order by o.name
  628. end
  629. else
  630. /*
  631. **  or print out all function name info
  632. */
  633. select distinct name = o.name, dll = substring(c.text,1,255)
  634.     from master.dbo.sysobjects o, master.dbo.syscomments c
  635.     where o.id = c.id
  636.         and o.xtype = N'X '
  637.     order by o.name
  638.  
  639. return (0) -- sp_helpextendedproc
  640. go
  641.  
  642.  
  643. ---------------------------------------------------------------
  644. raiserror('Now done creating the general system stored procs.  Start with miscellaneous tasks like xp_ and grants.',0,1)
  645. ---------------------------------------------------------------
  646. go
  647.  
  648. ---- Drop extended procs if they already exist now that sp_dropextendedproc has been created.
  649.  
  650. print ' '
  651. print 'Dropping any existing extended stored procedures.'
  652. go
  653.  
  654. if object_id('xp_addattach','X') IS NOT NULL
  655.     exec sp_dropextendedproc 'xp_addattach'
  656.  
  657. if object_id('xp_addmsgline','X') IS NOT NULL
  658.     exec sp_dropextendedproc 'xp_addmsgline'
  659.  
  660. if object_id('xp_cmdshell','X') IS NOT NULL
  661.     exec sp_dropextendedproc 'xp_cmdshell'
  662.  
  663. if object_id('sp_cursor','X') IS NOT NULL
  664.     exec sp_dropextendedproc 'sp_cursor'
  665.  
  666. if object_id('xp_userlock','X') IS NOT NULL
  667.     exec sp_dropextendedproc 'xp_userlock'
  668.  
  669. if object_id('sp_cursorclose','X') IS NOT NULL
  670.     exec sp_dropextendedproc 'sp_cursorclose'
  671.  
  672. if object_id('sp_cursorfetch','X') IS NOT NULL
  673.     exec sp_dropextendedproc 'sp_cursorfetch'
  674.  
  675. if object_id('sp_cursoropen','X') IS NOT NULL
  676.     exec sp_dropextendedproc 'sp_cursoropen'
  677.  
  678. if object_id('sp_cursoroption','X') IS NOT NULL
  679.     exec sp_dropextendedproc 'sp_cursoroption'
  680.  
  681. if object_id('xp_deletemail','X') IS NOT NULL
  682.     exec sp_dropextendedproc 'xp_deletemail'
  683.  
  684. if object_id('xp_enumgroups','X') IS NOT NULL
  685.     exec sp_dropextendedproc 'xp_enumgroups'
  686.  
  687. if object_id('xp_findnextmsg','X') IS NOT NULL
  688.     exec sp_dropextendedproc 'xp_findnextmsg'
  689.  
  690. if object_id('xp_logevent','X') IS NOT NULL
  691.     exec sp_dropextendedproc 'xp_logevent'
  692.  
  693. if object_id('xp_loginconfig','X') IS NOT NULL
  694.     exec sp_dropextendedproc 'xp_loginconfig'
  695.  
  696. if object_id('xp_logininfo','X') IS NOT NULL
  697.     exec sp_dropextendedproc 'xp_logininfo'
  698.  
  699. if object_id('xp_loginmail','X') IS NOT NULL
  700.     exec sp_dropextendedproc 'xp_loginmail'
  701.  
  702. if object_id('xp_logoffmail','X') IS NOT NULL
  703.     exec sp_dropextendedproc 'xp_logoffmail'
  704.  
  705. if object_id('xp_mailproclist','X') IS NOT NULL
  706.     exec sp_dropextendedproc 'xp_mailproclist'
  707.  
  708. if object_id('xp_msver','X') IS NOT NULL
  709.     exec sp_dropextendedproc 'xp_msver'
  710.  
  711. if object_id('xp_prepmsg','X') IS NOT NULL
  712.     exec sp_dropextendedproc 'xp_prepmsg'
  713.  
  714. if object_id('xp_readmail','X') IS NOT NULL
  715.     exec sp_dropextendedproc 'xp_readmail'
  716.  
  717. if object_id('xp_sendmail','X') IS NOT NULL
  718.     exec sp_dropextendedproc 'xp_sendmail'
  719.  
  720. if object_id('xp_sendmsg','X') IS NOT NULL
  721.     exec sp_dropextendedproc 'xp_sendmsg'
  722.  
  723. if object_id('xp_sprintf','X') IS NOT NULL
  724.     exec sp_dropextendedproc 'xp_sprintf'
  725.  
  726. if object_id('xp_sscanf','X') IS NOT NULL
  727.     exec sp_dropextendedproc 'xp_sscanf'
  728.  
  729. if object_id('xp_startmail','X') IS NOT NULL
  730.     exec sp_dropextendedproc 'xp_startmail'
  731.  
  732. if object_id('xp_stopmail','X') IS NOT NULL
  733.     exec sp_dropextendedproc 'xp_stopmail'
  734.  
  735. if object_id('xp_get_mapi_default_profile','X') IS NOT NULL
  736.     exec sp_dropextendedproc 'xp_get_mapi_default_profile'
  737.  
  738. if object_id('xp_get_mapi_profiles','X') IS NOT NULL
  739.     exec sp_dropextendedproc 'xp_get_mapi_profiles'
  740.  
  741. if object_id('xp_test_mapi_profile','X') IS NOT NULL
  742.     exec sp_dropextendedproc 'xp_test_mapi_profile'
  743. go
  744.  
  745. if object_id('sp_bindsession','X') IS NOT NULL
  746.     exec sp_dropextendedproc 'sp_bindsession'
  747.  
  748. if object_id('sp_getbindtoken','X') IS NOT NULL
  749.     exec sp_dropextendedproc 'sp_getbindtoken'
  750.  
  751. if object_id('sp_createorphan','X') IS NOT NULL
  752.     exec sp_dropextendedproc 'sp_createorphan'
  753.  
  754. if object_id('sp_droporphans','X') IS NOT NULL
  755.     exec sp_dropextendedproc 'sp_droporphans'
  756.  
  757. if object_id('sp_sdidebug','X') IS NOT NULL
  758.     exec sp_dropextendedproc 'sp_sdidebug'
  759.  
  760. if object_id('sp_executesql','X') IS NOT NULL
  761.     exec sp_dropextendedproc 'sp_executesql'
  762.  
  763. if object_id('sp_stmtpermissions','X') IS NOT NULL
  764.     exec sp_dropextendedproc 'sp_stmtpermissions'
  765.  
  766. if object_id('sp_objpermissions','X') IS NOT NULL
  767.     exec sp_dropextendedproc 'sp_objpermissions'
  768.  
  769. if object_id('sp_prepare','X') IS NOT NULL
  770.     exec sp_dropextendedproc 'sp_prepare'
  771.  
  772. if object_id('sp_execute','X') IS NOT NULL
  773.     exec sp_dropextendedproc 'sp_execute'
  774.  
  775. if object_id('sp_prepexec','X') IS NOT NULL
  776.     exec sp_dropextendedproc 'sp_prepexec'
  777.  
  778. if object_id('sp_prepexecrpc','X') IS NOT NULL
  779.     exec sp_dropextendedproc 'sp_prepexecrpc'
  780.  
  781. if object_id('sp_unprepare','X') IS NOT NULL
  782.     exec sp_dropextendedproc 'sp_unprepare'
  783.  
  784. if object_id('sp_cursorprepare','X') IS NOT NULL
  785.     exec sp_dropextendedproc 'sp_cursorprepare'
  786.  
  787. if object_id('sp_cursorexecute','X') IS NOT NULL
  788.     exec sp_dropextendedproc 'sp_cursorexecute'
  789.  
  790. if object_id('sp_cursorprepexec','X') IS NOT NULL
  791.     exec sp_dropextendedproc 'sp_cursorprepexec'
  792.  
  793. if object_id('sp_cursorunprepare','X') IS NOT NULL
  794.     exec sp_dropextendedproc 'sp_cursorunprepare'
  795.  
  796. if object_id('sp_reset_connection','X') IS NOT NULL
  797.     exec sp_dropextendedproc 'sp_reset_connection'
  798.  
  799. if object_id('sp_getschemalock','X') IS NOT NULL
  800.     exec sp_dropextendedproc 'sp_getschemalock'
  801.  
  802. if object_id('sp_releaseschemalock','X') IS NOT NULL
  803.     exec sp_dropextendedproc 'sp_releaseschemalock'
  804.  
  805. if object_id('sp_xml_preparedocument','X') IS NOT NULL
  806.     exec sp_dropextendedproc 'sp_xml_preparedocument'
  807.  
  808. if object_id('sp_xml_removedocument','X') IS NOT NULL
  809.     exec sp_dropextendedproc 'sp_xml_removedocument'
  810.  
  811. -- The following four extended procs only appear in shiloh beta 1
  812. if object_id('sp_xml_insertfromxml','X') IS NOT NULL
  813.     exec sp_dropextendedproc 'sp_xml_insertfromxml'
  814.  
  815. if object_id('sp_xml_fetchintoxml','X') IS NOT NULL
  816.     exec sp_dropextendedproc 'sp_xml_fetchintoxml'
  817.  
  818. if object_id('sp_xml_removexml','X') IS NOT NULL
  819.     exec sp_dropextendedproc 'sp_xml_removexml'
  820.  
  821. if object_id('sp_xml_fetchdocument','X') IS NOT NULL
  822.     exec sp_dropextendedproc 'sp_xml_fetchdocument'
  823.  
  824. if object_id('sp_resyncprepare','X') IS NOT NULL
  825.     exec sp_dropextendedproc 'sp_resyncprepare'
  826.  
  827. if object_id('sp_resyncexecute','X') IS NOT NULL
  828.     exec sp_dropextendedproc 'sp_resyncexecute'
  829.  
  830. if object_id('sp_resyncexecutesql','X') IS NOT NULL
  831.     exec sp_dropextendedproc 'sp_resyncexecutesql'
  832.  
  833. if object_id('sp_resyncuniquetable','X') IS NOT NULL
  834.     exec sp_dropextendedproc 'sp_resyncuniquetable'
  835.  
  836. if object_id('sp_trace_create','X') IS NOT NULL
  837.     exec sp_dropextendedproc 'sp_trace_create'
  838.  
  839. if object_id('sp_trace_setevent','X') IS NOT NULL
  840.     exec sp_dropextendedproc 'sp_trace_setevent'
  841.  
  842. if object_id('sp_trace_setfilter','X') IS NOT NULL
  843.     exec sp_dropextendedproc 'sp_trace_setfilter'
  844.  
  845. if object_id('sp_trace_setstatus','X') IS NOT NULL
  846.     exec sp_dropextendedproc 'sp_trace_setstatus'
  847.  
  848. if object_id('sp_trace_generateevent','X') IS NOT NULL
  849.     exec sp_dropextendedproc 'sp_trace_generateevent'
  850.  
  851.  
  852. go
  853.  
  854.  
  855. -- Add extended stored procedures.
  856. print ' '
  857. print 'Adding extended stored procedures.'
  858. go
  859.  
  860. execute sp_addextendedproc 'xp_cmdshell'    ,'xplog70.dll'
  861. execute sp_addextendedproc 'xp_logevent'    ,'xplog70.dll'
  862. execute sp_addextendedproc 'xp_sprintf'    ,'xplog70.dll'
  863. execute sp_addextendedproc 'xp_sscanf'        ,'xplog70.dll'
  864. execute sp_addextendedproc 'xp_msver'        ,'xplog70.dll'
  865. execute sp_addextendedproc 'xp_enumgroups'    ,'xplog70.dll'
  866. go
  867.  
  868. -- Add mail enabling extended procedures
  869. --
  870. -- IA64 related change. Due to missing libraries from Exchange SQLMail procs 
  871. -- won't be available for Liberty B-1. Bug #352141
  872. --
  873. -- Stub will be there and will display a descriptive message
  874. -- Bug #360731
  875. --
  876. execute sp_addextendedproc 'xp_startmail'                ,'sqlmap70.dll'
  877. execute sp_addextendedproc 'xp_stopmail'                 ,'sqlmap70.dll'
  878. execute sp_addextendedproc 'xp_sendmail'                 ,'sqlmap70.dll'
  879. execute sp_addextendedproc 'xp_deletemail'               ,'sqlmap70.dll'
  880. execute sp_addextendedproc 'xp_findnextmsg'              ,'sqlmap70.dll'
  881. execute sp_addextendedproc 'xp_readmail'                 ,'sqlmap70.dll'
  882. execute sp_addextendedproc 'xp_get_mapi_default_profile' ,'sqlmap70.dll'
  883. execute sp_addextendedproc 'xp_get_mapi_profiles'        ,'sqlmap70.dll'
  884. execute sp_addextendedproc 'xp_test_mapi_profile'        ,'sqlmap70.dll'
  885.  
  886. go
  887.  
  888. --Add extended stored procedures for NT integrated login security.
  889. --
  890. execute sp_addextendedproc 'xp_loginconfig'    ,'xplog70.dll'
  891. go
  892.  
  893. -- Add extended stored procedures for cursor support.
  894. --
  895. execute sp_addextendedproc 'sp_cursor'        ,'(server internal)'
  896. execute sp_addextendedproc 'sp_cursorclose'    ,'(server internal)'
  897. execute sp_addextendedproc 'sp_cursorfetch'    ,'(server internal)'
  898. execute sp_addextendedproc 'sp_cursoropen'    ,'(server internal)'
  899. execute sp_addextendedproc 'sp_cursoroption'    ,'(server internal)'
  900. go
  901.  
  902. -- Add extended stored procedures for bound session support.
  903. --
  904. execute sp_addextendedproc 'sp_bindsession'    ,'(server internal)'
  905. execute sp_addextendedproc 'sp_getbindtoken'    ,'(server internal)'
  906. go
  907.  
  908. -- Add extended stored procedures for orphaned text support for ODBC
  909. --
  910. execute sp_addextendedproc 'sp_createorphan' ,'(server internal)'
  911. execute sp_addextendedproc 'sp_droporphans' ,'(server internal)'
  912. go
  913.  
  914. -- Add extended stored procedures for XML text support
  915. --
  916. execute sp_addextendedproc 'sp_xml_preparedocument' ,'(server internal)'
  917. execute sp_addextendedproc 'sp_xml_removedocument' ,'(server internal)'
  918.  
  919. go
  920.  
  921. -- Add extended stored procedures for SQLTrace support
  922. --
  923. execute sp_addextendedproc 'sp_trace_create'        ,'(server internal)'
  924. execute sp_addextendedproc 'sp_trace_setevent'        ,'(server internal)'
  925. execute sp_addextendedproc 'sp_trace_setfilter'        ,'(server internal)'
  926. execute sp_addextendedproc 'sp_trace_setstatus'        ,'(server internal)'
  927. execute sp_addextendedproc 'sp_trace_generateevent'    ,'(server internal)'
  928. go
  929.  
  930. -- This xproc will be used for SQL debugging and will be invoked either via RPC or SQL language.
  931. --
  932. execute sp_addextendedproc 'sp_sdidebug'    ,'(server internal)'
  933. go
  934.  
  935. -- This xproc will be used for server support for Prepare-Execute
  936. --
  937. execute sp_addextendedproc 'sp_executesql'    ,'(server internal)'
  938. go
  939.  
  940. -- Add extended stored procedures for application locks
  941. --
  942. execute sp_addextendedproc 'xp_userlock'    ,'(server internal)'
  943. go
  944.  
  945. -- Starfter requested security proc
  946. --
  947. execute sp_addextendedproc 'sp_prepare'    ,'(server internal)'
  948. go
  949. execute sp_addextendedproc 'sp_execute'    ,'(server internal)'
  950. go
  951. execute sp_addextendedproc 'sp_prepexec'    ,'(server internal)'
  952. go
  953. execute sp_addextendedproc 'sp_prepexecrpc'    ,'(server internal)'
  954. go
  955. execute sp_addextendedproc 'sp_unprepare'    ,'(server internal)'
  956. go
  957. execute sp_addextendedproc 'sp_cursorprepare'    ,'(server internal)'
  958. go
  959. execute sp_addextendedproc 'sp_cursorexecute'    ,'(server internal)'
  960. go
  961. execute sp_addextendedproc 'sp_cursorprepexec'    ,'(server internal)'
  962. go
  963. execute sp_addextendedproc 'sp_cursorunprepare'    ,'(server internal)'
  964. go
  965.  
  966. -- This xproc will be used for server support for connection-caching
  967. --
  968. execute sp_addextendedproc 'sp_reset_connection','(server internal)'
  969. go
  970.  
  971. -- This xproc will be used for server support of schema locks
  972. execute sp_addextendedproc 'sp_getschemalock','(server internal)'
  973. execute sp_addextendedproc 'sp_releaseschemalock','(server internal)'
  974. go
  975.  
  976. -- Add the access resync query extended proc
  977. execute sp_addextendedproc 'sp_resyncprepare'    ,'(server internal)'
  978. go
  979. execute sp_addextendedproc 'sp_resyncexecute'    ,'(server internal)'
  980. go
  981. execute sp_addextendedproc 'sp_resyncexecutesql'    ,'(server internal)'
  982. go
  983. execute sp_addextendedproc 'sp_resyncuniquetable'    ,'(server internal)'
  984. go
  985.  
  986. -- UPDATE A VIEW'S METADATA TO REFLECT CHANGES IN UNDERLYING TABLES --
  987. if object_id('sp_refreshview','X') IS NOT NULL
  988.     exec sp_dropextendedproc 'sp_refreshview'
  989. execute sp_addextendedproc 'sp_refreshview','(server internal)'
  990. grant execute on sp_refreshview to public
  991. go
  992.  
  993. -- SP_SETLOGIN USED BY AGENT
  994. if object_id('sp_setuserbylogin','X') IS NOT NULL
  995.     exec sp_dropextendedproc 'sp_setuserbylogin'
  996. execute sp_addextendedproc 'sp_setuserbylogin','(server internal)'
  997. go
  998. grant execute on sp_setuserbylogin to public
  999. go
  1000. exec sp_MS_marksystemobject 'sp_setuserbylogin'
  1001. go
  1002.  
  1003. -------------------------------------
  1004. raiserror('Creating the general purpose System Stored Procedures ....',0,1)
  1005. -------------------------------------
  1006. go
  1007.  
  1008.  
  1009. raiserror(15339,-1,-1,'sp_user_counter1 - N')
  1010. go
  1011.  
  1012. create proc sp_user_counter1 @newvalue int as
  1013. dbcc setinstance ('SQLServer:User Settable', 'Query', 'User counter 1', @newvalue)
  1014. go
  1015. create proc sp_user_counter2 @newvalue int as
  1016. dbcc setinstance ('SQLServer:User Settable', 'Query', 'User counter 2', @newvalue)
  1017. go
  1018. create proc sp_user_counter3 @newvalue int as
  1019. dbcc setinstance ('SQLServer:User Settable', 'Query', 'User counter 3', @newvalue)
  1020. go
  1021. create proc sp_user_counter4 @newvalue int as
  1022. dbcc setinstance ('SQLServer:User Settable', 'Query', 'User counter 4', @newvalue)
  1023. go
  1024. create proc sp_user_counter5 @newvalue int as
  1025. dbcc setinstance ('SQLServer:User Settable', 'Query', 'User counter 5', @newvalue)
  1026. go
  1027. create proc sp_user_counter6 @newvalue int as
  1028. dbcc setinstance ('SQLServer:User Settable', 'Query', 'User counter 6', @newvalue)
  1029. go
  1030. create proc sp_user_counter7 @newvalue int as
  1031. dbcc setinstance ('SQLServer:User Settable', 'Query', 'User counter 7', @newvalue)
  1032. go
  1033. create proc sp_user_counter8 @newvalue int as
  1034. dbcc setinstance ('SQLServer:User Settable', 'Query', 'User counter 8', @newvalue)
  1035. go
  1036. create proc sp_user_counter9 @newvalue int as
  1037. dbcc setinstance ('SQLServer:User Settable', 'Query', 'User counter 9', @newvalue)
  1038. go
  1039. create proc sp_user_counter10 @newvalue int as
  1040. dbcc setinstance ('SQLServer:User Settable', 'Query', 'User counter 10', @newvalue)
  1041. go
  1042.  
  1043.  
  1044. --perfmon
  1045. raiserror(15339,-1,-1,'sp_blockcnt')
  1046. go
  1047. create procedure sp_blockcnt --- 1996/04/08 00:00
  1048. as
  1049. select blockedusers=count(*) from master.dbo.sysprocesses where blocked <> 0
  1050. go
  1051.  
  1052.  
  1053.  
  1054. --new query to watch max tempdbspace from perfmon
  1055. raiserror(15339,-1,-1,'sp_tempdbspace')
  1056. go
  1057. create proc sp_tempdbspace --- 1996/04/08 00:00
  1058. as
  1059.  
  1060. declare @dbsize dec(15,0)
  1061. declare @freespace dec(15,0)
  1062. declare @spaceused dec(15,0)
  1063.  
  1064. select @dbsize = sum(convert(dec(15),size))
  1065.                from tempdb.dbo.sysfiles
  1066.  
  1067. select  database_name = 'tempdb',
  1068.                database_size = (@dbsize / 128),
  1069.            spaceused=(select (sum(convert(dec(15),reserved))/128)
  1070.                    from tempdb..sysindexes
  1071.         where indid in (0, 1, 255))
  1072. go
  1073.  
  1074.  
  1075.  
  1076.  
  1077. raiserror(15339,-1,-1,'sp_dboption')
  1078. go
  1079. /*ANSI_NULLS ON  for creation of sp_dboption*/
  1080. set ansi_nulls on
  1081. go
  1082. create procedure sp_dboption  -- 1999/08/09 18:25
  1083. @dbname sysname = NULL,     /* database name to change */
  1084. @optname varchar(35) = NULL,  /* option name to turn on/off */
  1085. @optvalue varchar(10) = NULL  /* true or false */
  1086. as
  1087.  
  1088. set nocount    on
  1089.  
  1090. declare @dbid int         /* dbid of the database */
  1091. declare @catvalue int     /* number of category option */
  1092. declare @optcount int      /* number of options like @optname */
  1093. declare @allstatopts int    /* bit map off all options stored in sysdatqabases.status
  1094.                             ** that can be set by sp_dboption. */
  1095. declare @alloptopts int    /* bit map off all options stored in sysdatqabases.status
  1096.                             ** that can be set by sp_dboption. */
  1097. declare @allcatopts int    /* bit map off all options stored in sysdatqabases.category
  1098.                             ** that can be set by sp_dboption. */
  1099. declare @exec_stmt nvarchar(550)
  1100. declare @fulloptname varchar(35)
  1101. declare @alt_optname varchar(50)
  1102. declare @alt_optvalue varchar(30)
  1103.  
  1104. declare @status int
  1105.  
  1106. /*
  1107. **  If no @dbname given, just list the possible dboptions.
  1108. **  Only certain status bits may be set or cleared by sp_dboption.
  1109. */
  1110.  
  1111. /*
  1112. ** Get bitmap of all options that can be set by sp_dboption.
  1113. */
  1114. select @allstatopts=number from master.dbo.spt_values where type = 'D'
  1115.    and name = 'ALL SETTABLE OPTIONS'
  1116.  
  1117. select @allcatopts=number from master.dbo.spt_values where type = 'DC'
  1118.    and name = 'ALL SETTABLE OPTIONS'
  1119.  
  1120. select @alloptopts=number from master.dbo.spt_values where type = 'D2'
  1121.    and name = 'ALL SETTABLE OPTIONS'
  1122.  
  1123. if @dbname is null
  1124. begin
  1125.    select 'Settable database options:' = name
  1126.       from master.dbo.spt_values
  1127.       where (type = 'D'
  1128.             and number & @allstatopts <> 0
  1129.             and number not in (0,@allstatopts))  /* Eliminate non-option entries */
  1130.          or (type = 'DC'
  1131.             and number & @allcatopts <> 0
  1132.             and number not in (0,@allcatopts))
  1133.          or (type = 'D2'
  1134.             and number & @alloptopts <> 0
  1135.             and number not in (0,@alloptopts))
  1136.       order by name
  1137.    return (0)
  1138. end
  1139.  
  1140. /*
  1141. **  Verify the database name and get info
  1142. */
  1143. select @dbid = dbid
  1144. from master.dbo.sysdatabases
  1145. where name = @dbname
  1146.  
  1147. /*
  1148. **  If @dbname not found, say so and list the databases.
  1149. */
  1150. if @dbid is null
  1151.    begin
  1152.       raiserror(15010,-1,-1,@dbname)
  1153.       print ' '
  1154.       select 'Available databases:' = name
  1155.          from master.dbo.sysdatabases
  1156.       return (1)
  1157.    end
  1158.  
  1159. /*
  1160. ** If no option was supplied, display current settings.
  1161. */
  1162. if @optname is null
  1163.    begin
  1164.       select 'The following options are set:' = v.name
  1165.          from master.dbo.spt_values v, master.dbo.sysdatabases d
  1166.             where d.name=@dbname
  1167.                and ((number & @allstatopts <> 0
  1168.                      and number not in (-1,@allstatopts)
  1169.                      and v.type = 'D'
  1170.                      and (v.number & d.status)=v.number)
  1171.                  or (number & @allcatopts <> 0
  1172.                      and number not in (-1,@allcatopts)
  1173.                      and v.type = 'DC'
  1174.                      and d.category & v.number <> 0)
  1175.                  or (number & @alloptopts <> 0
  1176.                      and number not in (-1,@alloptopts)
  1177.                      and v.type = 'D2'
  1178.                      and d.status2 & v.number <> 0))
  1179.       return(0)
  1180.    end
  1181.  
  1182.  
  1183. if lower(@optvalue) not in ('true', 'false', 'on', 'off') and @optvalue is not null
  1184.    begin
  1185.       raiserror(15241,-1,-1)
  1186.       return (1)
  1187.    end
  1188.  
  1189. /*
  1190. **  Use @optname and try to find the right option.
  1191. **  If there isn't just one, print appropriate diagnostics and return.
  1192. */
  1193. select @optcount = count(*) ,@fulloptname = min(name)
  1194.       from master.dbo.spt_values
  1195.       where lower(name) like '%' + lower(@optname) + '%'
  1196.          and ((type = 'D'
  1197.               and number & @allstatopts <> 0
  1198.               and number not in (-1,@allstatopts))
  1199.           or (type = 'DC'
  1200.               and number & @allcatopts <> 0
  1201.               and number not in (-1,@allcatopts))
  1202.             or (type = 'D2'
  1203.               and number & @alloptopts <> 0
  1204.               and number not in (-1,@alloptopts)))
  1205.  
  1206. /*
  1207. **  If no option, show the user what the options are.
  1208. */
  1209. if @optcount = 0
  1210.    begin
  1211.       raiserror(15011,-1,-1,@optname)
  1212.       print ' '
  1213.  
  1214.       select 'Settable database options:' = name
  1215.          from master.dbo.spt_values
  1216.          where (type = 'D'
  1217.                and number & @allstatopts <> 0
  1218.                and number not in (-1,@allstatopts))  /* Eliminate non-option entries */
  1219.             or (type = 'DC'
  1220.                and number & @allcatopts <> 0
  1221.                and number not in (-1,@allcatopts))
  1222.             or (type = 'D2'
  1223.                and number & @alloptopts <> 0
  1224.                and number not in (-1,@alloptopts))
  1225.          order by name
  1226.  
  1227.       return (1)
  1228.    end
  1229.  
  1230.  
  1231. /*
  1232. **  If more than one option like @optname, show the duplicates and return.
  1233. */
  1234. if @optcount > 1
  1235.    begin
  1236.       raiserror(15242,-1,-1,@optname)
  1237.       print ' '
  1238.  
  1239.       select duplicate_options = name
  1240.          from master.dbo.spt_values
  1241.          where lower(name) like '%' + lower(@optname) + '%'
  1242.             and ((type = 'D'
  1243.                  and number & @allstatopts <> 0
  1244.                  and number not in (-1,@allstatopts))
  1245.               or (type = 'DC'
  1246.                  and number & @allcatopts <> 0
  1247.                  and number not in (-1,@allcatopts))
  1248.               or (type = 'D2'
  1249.                  and number & @alloptopts <> 0
  1250.                  and number not in (-1,@alloptopts))
  1251.                 )
  1252.       return (1)
  1253.    end
  1254.  
  1255.  
  1256. /*
  1257. **  Just want to see current setting of specified option.
  1258. */
  1259. if @optvalue is null
  1260. begin
  1261.       select OptionName = v.name
  1262.  
  1263.             ,CurrentSetting =
  1264.                CASE
  1265.                   When ( ((v.number & d.status) = v.number
  1266.                           and v.type = 'D')
  1267.                       or (d.category & v.number <> 0
  1268.                            and v.type = 'DC')
  1269.                       or (d.status2 & v.number <> 0
  1270.                            and v.type = 'D2')
  1271.                        )
  1272.                      Then 'ON'
  1273.                   When NOT
  1274.                        ( ((v.number & d.status) = v.number
  1275.                           and v.type = 'D')
  1276.                       or (d.category & v.number <> 0
  1277.                            and v.type = 'DC')
  1278.                       or (d.status2 & v.number <> 0
  1279.                            and v.type = 'D2')
  1280.                        )
  1281.                      Then 'off'
  1282.                END
  1283.  
  1284.          from master.dbo.spt_values v, master.dbo.sysdatabases d
  1285.             where d.name=@dbname
  1286.                and ((v.number & @allstatopts <> 0
  1287.                      and v.number not in (-1,@allstatopts)   /* Eliminate non-option entries */
  1288.                      and v.type = 'D')
  1289.                  or (v.number & @allcatopts <> 0
  1290.                      and v.number not in (-1,@allcatopts)   /* Eliminate non-option entries */
  1291.                      and v.type = 'DC')
  1292.                  or (v.number & @alloptopts <> 0
  1293.                      and v.number not in (-1,@alloptopts)   /* Eliminate non-option entries */
  1294.                      and v.type = 'D2')
  1295.                    )
  1296.                 and lower(v.name) = lower(@fulloptname)
  1297.  
  1298.    return (0)
  1299. end
  1300.  
  1301.  
  1302. select @catvalue = 0
  1303. select @catvalue = number
  1304.       from master.dbo.spt_values
  1305.       where lower(name) = lower(@fulloptname)
  1306.       and type = 'DC'
  1307.  
  1308. /* if setting replication option, call sp_replicationdboption directly */
  1309. if (@catvalue <> 0)
  1310.     begin
  1311.         if lower(@optvalue) in ('true', 'on')
  1312.             begin
  1313.                 select @alt_optvalue = 'true'
  1314.             end
  1315.         else
  1316.             begin
  1317.                 select @alt_optvalue = 'false'
  1318.             end
  1319.  
  1320.         select alt_optname = quotename(@fulloptname, '''')
  1321.         select @exec_stmt = quotename(@dbname, '[')   + '.dbo.sp_replicationdboption'
  1322.  
  1323.         if @catvalue = 1
  1324.             begin
  1325.                 select @alt_optname  = 'publish'
  1326.             end
  1327.         if @catvalue = 2
  1328.             begin
  1329.                 select @alt_optname  = 'subscribe'
  1330.             end
  1331.         if @catvalue = 4
  1332.             begin
  1333.                 select @alt_optname  = 'merge publish'
  1334.             end
  1335.  
  1336.         exec @exec_stmt @dbname, @alt_optname, @alt_optvalue
  1337.         return (0)
  1338.     end
  1339.  
  1340.  
  1341. /* call Alter Database to set options */
  1342.  
  1343. /* set option value in alter database*/
  1344. if lower(@optvalue) in ('true', 'on')
  1345.    begin
  1346.         select @alt_optvalue = 'ON'
  1347.    end
  1348.  
  1349. else
  1350.     begin
  1351.         select @alt_optvalue = 'OFF'
  1352.     end
  1353.  
  1354. /* if Cross DB Ownership Chaining is the option. Set it and get out */
  1355. if lower(@fulloptname) = 'db chaining'
  1356.     begin
  1357.     
  1358.     -- CHECK PERMISSIONS (Note: All sysadmins are dbo) --
  1359.     if not (is_srvrolemember('sysadmin') = 1)
  1360.     begin
  1361.         raiserror(15247,-1,-1)
  1362.         return(1)
  1363.     end
  1364.  
  1365.     -- CANT SET IN ANY OF OF MASTER/MODEL/TEMPDB --
  1366.     if lower(@dbname) in ('master', 'model', 'tempdb') or
  1367.        (lower(@dbname) ='msdb' and @alt_optvalue = 'OFF')
  1368.     begin
  1369.         raiserror(5600,-1,-1)
  1370.         return(1)
  1371.     end
  1372.  
  1373.     -- ERROR IF IN USER TRANSACTION --
  1374.     if @@trancount > 0
  1375.     begin
  1376.         raiserror(15289,-1,-1)
  1377.         return (1)
  1378.     end
  1379.  
  1380.    -- MAKE THE FOLLOWING REMOVE/REMAP/DELETES ATOMIC --
  1381.     begin transaction
  1382.  
  1383.     select @status = status2 from master.dbo.sysdatabases where name = @dbname
  1384.     if @alt_optvalue = 'ON'
  1385.         set @status = @status | 1024
  1386.     else
  1387.         select @status = @status & (~ 1024)
  1388.     update master.dbo.sysdatabases set status2 = @status where name = @dbname
  1389.  
  1390.  
  1391.     -- REFLECT NEW STATUS IN SYSDATABASES --
  1392.     commit transaction
  1393.  
  1394.     -- CHECKPOINT DATABASE TO FORCE CHANGES TO IN-MEMORY STRUCTURE --
  1395.     select @exec_stmt = 'use ' +  quotename(@dbname, '[')   + ' checkpoint'         
  1396.     exec (@exec_stmt)        
  1397.  
  1398.     return (0) -- end of set db chaining/user info in doubt  option
  1399.     end
  1400.  
  1401.  
  1402. /* set option name in alter database */
  1403. if lower(@fulloptname) = 'auto create statistics'
  1404.     begin
  1405.         select @alt_optname = 'AUTO_CREATE_STATISTICS'
  1406.     end
  1407.  
  1408. if lower(@fulloptname) = 'auto update statistics'
  1409.     begin
  1410.         select @alt_optname = 'AUTO_UPDATE_STATISTICS'
  1411.     end
  1412.  
  1413. if lower(@fulloptname) = 'autoclose'
  1414.     begin
  1415.         select @alt_optname = 'AUTO_CLOSE'
  1416.     end
  1417.  
  1418. if lower(@fulloptname) = 'autoshrink'
  1419.     begin
  1420.         select @alt_optname = 'AUTO_SHRINK'
  1421.     end
  1422.  
  1423. if lower(@fulloptname) = 'ansi padding'
  1424.     begin
  1425.         select @alt_optname = 'ANSI_PADDING'
  1426.     end
  1427.  
  1428. if lower(@fulloptname) = 'arithabort'
  1429.     begin
  1430.         select @alt_optname = 'ARITHABORT'
  1431.     end
  1432.  
  1433. if lower(@fulloptname) = 'numeric roundabort'
  1434.     begin
  1435.         select @alt_optname = 'NUMERIC_ROUNDABORT'
  1436.     end
  1437.  
  1438. if lower(@fulloptname) = 'ansi null default'
  1439.     begin
  1440.         select @alt_optname = 'ANSI_NULL_DEFAULT'
  1441.     end
  1442.  
  1443. if lower(@fulloptname) = 'ansi nulls'
  1444.     begin
  1445.         select @alt_optname = 'ANSI_NULLS'
  1446.     end
  1447.  
  1448. if lower(@fulloptname) = 'ansi warnings'
  1449.     begin
  1450.         select @alt_optname = 'ANSI_WARNINGS'
  1451.     end
  1452.  
  1453. if lower(@fulloptname) = 'concat null yields null'
  1454.     begin
  1455.         select @alt_optname = 'CONCAT_NULL_YIELDS_NULL'
  1456.     end
  1457.  
  1458. if lower(@fulloptname) = 'cursor close on commit'
  1459.     begin
  1460.         select @alt_optname = 'CURSOR_CLOSE_ON_COMMIT'
  1461.     end
  1462.  
  1463. if lower(@fulloptname) = 'torn page detection'
  1464.     begin
  1465.         select @alt_optname = 'TORN_PAGE_DETECTION'
  1466.     end
  1467.  
  1468. if lower(@fulloptname) = 'quoted identifier'
  1469.     begin
  1470.         select @alt_optname = 'QUOTED_IDENTIFIER'
  1471.     end
  1472.  
  1473. if lower(@fulloptname) = 'recursive triggers'
  1474.     begin
  1475.         select @alt_optname = 'RECURSIVE_TRIGGERS'
  1476.     end
  1477.  
  1478. if lower(@fulloptname) = 'default to local cursor'
  1479.     begin
  1480.         select @alt_optname = 'CURSOR_DEFAULT'
  1481.  
  1482.         if @alt_optvalue = 'ON'
  1483.            begin
  1484.                 select @alt_optvalue = 'LOCAL'
  1485.            end
  1486.  
  1487.         else
  1488.             begin
  1489.                 select @alt_optvalue = 'GLOBAL'
  1490.             end
  1491.     end
  1492.  
  1493. if lower(@fulloptname) = 'offline'
  1494.     begin
  1495.         if @alt_optvalue = 'ON'
  1496.            begin
  1497.                 select @alt_optname = 'OFFLINE'
  1498.            end
  1499.  
  1500.         else
  1501.             begin
  1502.                 select @alt_optname = 'ONLINE'
  1503.             end
  1504.         select @alt_optvalue = ''
  1505.     end
  1506.  
  1507. if lower(@fulloptname) = 'read only'
  1508.     begin
  1509.         if @alt_optvalue = 'ON'
  1510.            begin
  1511.                 select @alt_optname = 'READ_ONLY'
  1512.            end
  1513.  
  1514.         else
  1515.             begin
  1516.                 select @alt_optname = 'READ_WRITE'
  1517.             end
  1518.         select @alt_optvalue = ''
  1519.     end
  1520.  
  1521. if lower(@fulloptname) = 'dbo use only'
  1522.     begin
  1523.         if @alt_optvalue = 'ON'
  1524.             begin
  1525.                 if databaseproperty(@dbname, 'IsSingleUser') = 1
  1526.                     begin
  1527.                         raiserror(5066,-1,-1);
  1528.                         return (1)
  1529.                     end
  1530.                 select @alt_optname = 'RESTRICTED_USER'
  1531.             end
  1532.  
  1533.         else
  1534.             begin
  1535.                 if databaseproperty(@dbname, 'IsDBOOnly') = 0
  1536.                     begin
  1537.                         return (0)
  1538.                     end
  1539.                 select @alt_optname = 'MULTI_USER'
  1540.             end
  1541.  
  1542.         select @alt_optvalue = ''
  1543.     end
  1544.  
  1545. if lower(@fulloptname) = 'single user'
  1546.     begin
  1547.         if @alt_optvalue = 'ON'
  1548.            begin
  1549.                 if databaseproperty(@dbname, 'ISDBOOnly') = 1
  1550.                     begin
  1551.                         raiserror(5066,-1,-1);
  1552.                         return (1)
  1553.                     end
  1554.                 select @alt_optname = 'SINGLE_USER'
  1555.            end
  1556.  
  1557.         else
  1558.             begin
  1559.                 if databaseproperty(@dbname, 'IsSingleUser') = 0
  1560.                     begin
  1561.                         return (0)
  1562.                     end
  1563.                 select @alt_optname = 'MULTI_USER'
  1564.             end
  1565.         select @alt_optvalue = ''
  1566.     end
  1567.  
  1568. if lower(@fulloptname) = 'select into/bulkcopy'
  1569.     begin
  1570.         select @alt_optname = 'RECOVERY'
  1571.  
  1572.         if @alt_optvalue = 'ON'
  1573.            begin
  1574.                 if databaseproperty(@dbname, 'IsTrunclog') = 1
  1575.                     begin
  1576.                         select @alt_optvalue = 'RECMODEL_70BACKCOMP'
  1577.                     end
  1578.                 else
  1579.                     begin
  1580.                         select @alt_optvalue = 'BULK_LOGGED'
  1581.                     end
  1582.            end
  1583.  
  1584.         else
  1585.             begin
  1586.                 if databaseproperty(@dbname, 'IsTrunclog') = 1
  1587.                     begin
  1588.                         select @alt_optvalue = 'SIMPLE'
  1589.                     end
  1590.                 else
  1591.                     begin
  1592.                         select @alt_optvalue = 'FULL'
  1593.                     end
  1594.             end
  1595.     end
  1596.  
  1597. if lower(@fulloptname) = 'trunc. log on chkpt.'
  1598.     begin
  1599.         select @alt_optname = 'RECOVERY'
  1600.  
  1601.         if @alt_optvalue = 'ON'
  1602.             begin
  1603.                 if databaseproperty(@dbname, 'IsBulkCopy') = 1
  1604.                     begin
  1605.                         select @alt_optvalue = 'RECMODEL_70BACKCOMP'
  1606.                     end
  1607.                 else
  1608.                     begin
  1609.                         select @alt_optvalue = 'SIMPLE'
  1610.                     end
  1611.             end
  1612.  
  1613.         else
  1614.             begin
  1615.                 if databaseproperty(@dbname, 'IsBulkCopy') = 1
  1616.                     begin
  1617.                         select @alt_optvalue = 'BULK_LOGGED'
  1618.                     end
  1619.                 else
  1620.                     begin
  1621.                         select @alt_optvalue = 'FULL'
  1622.                     end
  1623.             end
  1624.     end
  1625.  
  1626. /* construct the ALTER DATABASE command string */
  1627. select @exec_stmt = 'ALTER DATABASE ' + quotename(@dbname) +' SET ' + @alt_optname + ' ' + @alt_optvalue + ' WITH NO_WAIT'
  1628. exec (@exec_stmt)
  1629.  
  1630. if @@error <> 0
  1631.     begin
  1632.         raiserror(15627,-1,-1)
  1633.         return (1)
  1634.     end
  1635. else
  1636.     begin
  1637.         return (0)
  1638.     end
  1639.  
  1640. return (0) -- sp_dboption
  1641. go
  1642. set ansi_nulls off
  1643. go
  1644. /*ANSI_NULLS OFF  for after creation of sp_dboption*/
  1645.  
  1646. checkpoint
  1647. go
  1648.  
  1649. raiserror(15339,-1,-1,'sp_dbcmptlevel')
  1650. go
  1651. /*ANSI_NULLS ON  for creation of sp_dbcmptlevel*/
  1652. set ansi_nulls on
  1653. go
  1654. create procedure sp_dbcmptlevel  -- 1997/04/15
  1655. @dbname sysname = NULL,        /* database name to change */
  1656. @new_cmptlevel tinyint = NULL OUTPUT    /* the new compatibility level to change to */
  1657. as
  1658.  
  1659. set nocount    on
  1660.  
  1661. declare @exec_stmt nvarchar(275)
  1662. declare @returncode    int
  1663. declare @comptlevel    float(8)
  1664. declare @dbid int                /* dbid of the database */
  1665. declare @dbsid varbinary(85)    /* id of the owner of the database */
  1666. declare @orig_cmptlevel tinyint    /* original compatibility level */
  1667. declare @input_cmptlevel tinyint    /* compatibility level passed in by user */
  1668.     ,@cmptlvl60 tinyint            /* compatibility to SQL Server Version 6.0 */
  1669.     ,@cmptlvl65 tinyint            /* compatibility to SQL Server Version 6.5 */
  1670.     ,@cmptlvl70 tinyint            /* compatibility to SQL Server Version 7.0 */
  1671.     ,@cmptlvl80 tinyint            /* compatibility to SQL Server Version 8.0 */
  1672. select  @cmptlvl60 = 60,
  1673.         @cmptlvl65 = 65,
  1674.         @cmptlvl70 = 70,
  1675.         @cmptlvl80 = 80
  1676.  
  1677.  
  1678. -- SP MUST BE CALLED AT ADHOC LEVEL --
  1679. if (@@nestlevel > 1)
  1680. begin
  1681.     raiserror(15432,-1,-1,'sp_dbcmptlevel')
  1682.     return (1)
  1683. end
  1684.  
  1685. /*
  1686. **  If no @dbname given, just list the valid compatibility level values.
  1687. */
  1688.  
  1689. if @dbname is null
  1690. begin
  1691.    raiserror (15048, -1, -1, @cmptlvl60, @cmptlvl65, @cmptlvl70, @cmptlvl80)
  1692.    return (0)
  1693. end
  1694.  
  1695. /*
  1696. **  Verify the database name and get info
  1697. */
  1698. select @dbid = dbid, @dbsid = sid ,@orig_cmptlevel = cmptlevel
  1699.    from master.dbo.sysdatabases
  1700.       where name = @dbname
  1701.  
  1702. /*
  1703. **  If @dbname not found, say so and list the databases.
  1704. */
  1705. if @dbid is null
  1706.    begin
  1707.       raiserror(15010,-1,-1,@dbname)
  1708.       print ' '
  1709.       select 'Available databases:' = name
  1710.          from master.dbo.sysdatabases
  1711.       return (1)
  1712.    end
  1713.  
  1714. /*
  1715. ** Now save the input compatibility level and initialize the return clevel
  1716. ** to be the current clevel
  1717. */
  1718. select @input_cmptlevel = @new_cmptlevel
  1719. select @new_cmptlevel = @orig_cmptlevel
  1720.  
  1721. /*
  1722. ** If no clevel was supplied, display and output current level.
  1723. */
  1724. if @input_cmptlevel is null
  1725.    begin
  1726.       raiserror(15054, -1, -1, @orig_cmptlevel)
  1727.       return(0)
  1728.    end
  1729.  
  1730. /*
  1731. ** We should not allow the user to change the compatibility level of the master database
  1732. */
  1733. if @dbid = db_id('master')
  1734.     begin
  1735.        raiserror(15417, -1, -1, @dbname)
  1736.        return (1)
  1737.     end
  1738.  
  1739. /*
  1740. ** If invalid clevel given, print usage and return error code
  1741. ** 'usage: sp_dbcmptlevel [dbname [, compatibilitylevel]]'
  1742. */
  1743. if @input_cmptlevel not in (@cmptlvl60, @cmptlvl65, @cmptlvl70, @cmptlvl80)
  1744.    begin
  1745.       raiserror(15416, -1, -1)
  1746.       print ' '
  1747.       raiserror (15048,
  1748.          -1, -1, @cmptlvl60, @cmptlvl65, @cmptlvl70, @cmptlvl80)
  1749.       return (1)
  1750.    end
  1751.  
  1752. /*
  1753. ** We should not allow the user to change the compatibility level if there exists IV or ICC
  1754. */
  1755. if @orig_cmptlevel = @cmptlvl80 and @input_cmptlevel < @cmptlvl80
  1756.     begin
  1757.         -- CHECK FOR INDEXED VIEWS OR INDEXED COMPUTED-COLUMNS
  1758.         if exists (select * from sysobjects where xtype = 'V' and id in (select id from sysindexes)) or
  1759.             exists (select * from sysobjects o join sysindexkeys k on o.id=k.id
  1760.                 where o.xtype = 'U' and ColumnProperty(k.id, col_name(k.id, k.colid), 'IsComputed') = 1)
  1761.             begin
  1762.                 -- Cannot set compat mode because database has a view or computed column that is indexed.
  1763.                 -- These indexes require an 8.0-compatible database.
  1764.                 raiserror(15414, -1, -1)
  1765.                 return (1)
  1766.             end
  1767.     end
  1768.  
  1769. /*
  1770. **  Only the SA or the dbo of @dbname can execute the update part
  1771. **  of this procedure so check.
  1772. */
  1773. if (not (is_srvrolemember('sysadmin') = 1)) and suser_sid() <> @dbsid
  1774.     -- ALSO ALLOW db_owner ONLY IF DB REQUESTED IS CURRENT DB
  1775.     and (@dbid <> db_id() or is_member('db_owner') <> 1)
  1776.    begin
  1777.       raiserror(15418,-1,-1)
  1778.       return (1)
  1779.    end
  1780.  
  1781. /*
  1782. ** We should not allow the user to change the compatibility level for
  1783. ** replicated or distributed databases
  1784. */
  1785. select @comptlevel =    case @input_cmptlevel
  1786.                             when 60 then 6.0
  1787.                             when 65 then 6.5
  1788.                             when 70 then 7.0
  1789.                             when 80 then 8.0
  1790.                         end
  1791.  
  1792. exec @returncode = sp_MSreplicationcompatlevel @dbname, @comptlevel
  1793.  
  1794. if @returncode <> 0
  1795.     begin
  1796.         raiserror(15306, -1, -1)
  1797.         return (1)
  1798.     end
  1799.  
  1800. /*
  1801. **  If we're in a transaction, disallow this since it might make recovery
  1802. **  impossible.
  1803. */
  1804. set implicit_transactions off
  1805. if @@trancount > 0
  1806.    begin
  1807.       raiserror(15002,-1,-1,'sp_dbcmptlevel')
  1808.       return (1)
  1809.    end
  1810.  
  1811.  
  1812. update master.dbo.sysdatabases set cmptlevel = @input_cmptlevel
  1813.       where dbid = @dbid
  1814.  
  1815. /*
  1816. **  CHECKPOINT the database that was changed.
  1817. */
  1818.  
  1819. select @exec_stmt = 'use ' +  quotename(@dbname, '[')   + ' checkpoint'
  1820. exec(@exec_stmt )
  1821. /*
  1822. ** If checkpoint unsuccessful, restore the old compatibility level,
  1823. ** otherwise update output clevel and flush all the SPs of this database
  1824. ** from the cache
  1825. */
  1826. if (@@error <> 0)
  1827.     begin
  1828.     update         master.dbo.sysdatabases
  1829.         set     cmptlevel = @orig_cmptlevel
  1830.         where     dbid   = @dbid
  1831.     end
  1832. else
  1833.     begin
  1834.     dbcc flushprocindb(@dbid)
  1835.     select @new_cmptlevel = @input_cmptlevel
  1836.     end
  1837.  
  1838. return (0) -- sp_dbcmptlevel
  1839. go
  1840. set ansi_nulls off
  1841. go
  1842. /*ANSI_NULLS OFF  for after creation of sp_dbcmptlevel*/
  1843.  
  1844. ---- Fallback 6.5 sprocs removed for 7.0 until re-coded from scratch to match new tables.
  1845. /************************  BEGIN-FALLBACK-STORED-PROCS ***********************/
  1846. raiserror(15339,-1,-1,'sp_fallback_MS_sel_fb_svr')
  1847. go
  1848.  
  1849. create procedure sp_fallback_MS_sel_fb_svr  --- 1997/05/30 02:44
  1850.     @pFallbackSvrName    character varying(30)   OUTPUT
  1851. as
  1852. /********1*********2*********3*********4*********5*********6*********7**
  1853.  
  1854.       This sproc is used by ODBC & DBLib when first connecting.
  1855.       This sproc will assign a null to the output parm.
  1856.       Note: This will need to be changed to return the name
  1857.             of the virtual server once WolfPack support is enabled.
  1858. *********1*********2*********3*********4*********5*********6*********7*/
  1859.  
  1860. Set nocount                   on
  1861. Set ansi_nulls                on
  1862.  
  1863. SELECT       @pFallbackSvrName   = null
  1864.  
  1865. Return 0
  1866. go
  1867.  
  1868. grant execute on sp_fallback_MS_sel_fb_svr to public
  1869. go
  1870.  
  1871. checkpoint
  1872. go
  1873. /*************************  END-FALLBACK-STORED-PROCS ************************/
  1874.  
  1875. raiserror(15339,-1,-1,'sp_validname')
  1876. go
  1877. CREATE PROCEDURE sp_validname
  1878.     @name            sysname,
  1879.     @raise_error    bit = 1
  1880. AS
  1881.     -----------------------------------------------------
  1882.     --    This SP checks for valid SQL-Server identifiers.
  1883.     --    For 7.0+, these are the very-simple checks below.
  1884.     --    All non-binary-zero (UNICODE) characters we just
  1885.     --    accept as being valid.
  1886.     -----------------------------------------------------
  1887.     declare @index    int
  1888.  
  1889.     Set nocount on
  1890.  
  1891.     -- Name cannot be NULL or empty ("")
  1892.     -- Blank identifiers (" ") are allowed
  1893.     IF (@name is null OR datalength(@name) = 0)
  1894.     begin
  1895.         if @raise_error = 1
  1896.             raiserror (15004,-1,-1)
  1897.         return (1)
  1898.     end
  1899.  
  1900.     -- Name cannot contain a binary-zero character
  1901.     select @index = charindex(convert(nchar(1),0x00), @name)
  1902.     while (@index <> 0)
  1903.     begin
  1904.         if unicode(substring(@name, @index, 1)) = 0
  1905.         begin
  1906.             if @raise_error = 1
  1907.                 raiserror(15006,-1,-1,@name)
  1908.             return (1)
  1909.         end
  1910.         if @index >= len(@name)
  1911.             select @index = 0
  1912.         else
  1913.         begin
  1914.             select @name = substring(@name, @index+1, len(@name)-@index)
  1915.             select @index = charindex(convert(nchar(1),0x00), @name)
  1916.         end
  1917.     end
  1918.  
  1919.     -- TH-TH-TH-THAT'S IT!
  1920.     return (0) -- sp_validname
  1921. go
  1922.  
  1923.  
  1924. raiserror(15339,-1,-1,'sp_validlang')
  1925. go
  1926. create procedure sp_validlang --- 1996/04/08 00:00
  1927. @name    sysname
  1928. as
  1929.  
  1930. /* Check to see if this language is in Syslanguages. */
  1931. if exists (select * from master.dbo.syslanguages where name = @name or alias = @name)
  1932.     or @name = N'us_english'
  1933.     return(0)
  1934.  
  1935. raiserror(15033,-1,-1,@name)
  1936. return (1) -- sp_validlang
  1937. go
  1938.  
  1939. checkpoint
  1940. go
  1941.  
  1942. raiserror(15339,-1,-1,'sp_addmessage')
  1943. go
  1944. create procedure sp_addmessage --- 1996/04/08 00:00
  1945. @msgnum int = null,        -- Number of new message.
  1946. @severity smallint = null,    -- Severity of new message.
  1947. @msgtext nvarchar(255) = null,    -- Text of new message.
  1948. @lang sysname = null,       -- language (name) of new message
  1949. @with_log varchar(5) = 'FALSE', -- Whether the message will ALWAYS go to the NT event log
  1950. @replace varchar(7) = null    -- Optional parameter to specify that
  1951.                 -- existing message with same number
  1952.                 -- should be overwritten.
  1953. as
  1954. declare @retcode int
  1955. declare @langid smallint
  1956. declare @msglangid smallint
  1957. declare @dlevel smallint
  1958.  
  1959.     -- Must be ServerAdmin to manage messages
  1960.     if is_srvrolemember('serveradmin') = 0
  1961.     begin
  1962.         raiserror(15247,-1,-1)
  1963.         return (1)
  1964.     end
  1965.  
  1966. if @msgnum is null or @severity is null or @msgtext is null
  1967.     begin
  1968.         raiserror(15071,-1,-1)
  1969.         return(1)
  1970.     end
  1971.  
  1972. /*
  1973. ** User defined messages must be > 50000.
  1974. */
  1975. if @msgnum <= 50000
  1976.     begin
  1977.         raiserror(15040,-1,-1)
  1978.         return(1)
  1979.     end
  1980.  
  1981. /*
  1982. ** Valid severity range for user defined messges is 1 to 25.
  1983. */
  1984. if @severity not between 1 and 25
  1985.     begin
  1986.         raiserror(15041,-1,-1)
  1987.         return(1)
  1988.     end
  1989.  
  1990. /*
  1991. ** Verify the language
  1992. */
  1993. if @lang is not null
  1994.     begin
  1995.         exec @retcode = sp_validlang @lang
  1996.         if @retcode <>  0
  1997.             return(1)
  1998.     end
  1999. else
  2000.     select @lang = @@language
  2001.  
  2002. /*
  2003. ** Get langid from syslanguages; us_english won't exist, so use 0.
  2004. */
  2005. select @langid = langid, @msglangid = msglangid
  2006.     from master.dbo.syslanguages where name = @lang or alias = @lang
  2007.  
  2008. select @langid = isnull(@langid, 0)
  2009. select @msglangid = isnull(@msglangid, 1033)
  2010.  
  2011. /*
  2012. ** @with_log must be 'TRUE' or 'FALSE'
  2013. */
  2014. if (upper(@with_log) not in ('TRUE', 'FALSE'))
  2015.     begin
  2016.         raiserror(15271,-1,-1)
  2017.         return (1)
  2018.     end
  2019.  
  2020. /*
  2021. ** Set the dlevel bit accordingly
  2022. */
  2023. if (rtrim(upper(@with_log)) = 'TRUE')
  2024.         select @dlevel = 0x80
  2025. else
  2026.         select @dlevel = 0x0
  2027.  
  2028. /*
  2029. ** If we're adding a non-us_english message, make sure the us_english version already exists.
  2030. */
  2031. if (@langid <> 0) and not exists (select * from master.dbo.sysmessages where error=@msgnum and msglangid = 1033)
  2032.     begin
  2033.         raiserror(15279,-1,-1,@lang)
  2034.         return(1)
  2035.     end
  2036.  
  2037. /*
  2038. ** If we're adding a non-us_english message, make sure that the severity matches that of the us_english version
  2039. */
  2040. if (@langid <> 0 ) and not exists (select * from master.dbo.sysmessages where error=@msgnum and severity=@severity and msglangid = 1033)
  2041.     begin
  2042.         declare @us_english_severity smallint
  2043.         select @us_english_severity = severity from master.dbo.sysmessages where error=@msgnum and msglangid = 1033
  2044.         raiserror(15304,-1,-1,@lang,@us_english_severity)
  2045.         return(1)
  2046.     end
  2047.  
  2048. /*
  2049. **  Does this message already exist, and if so are we REPLACEing it?
  2050. */
  2051. if (select count(*) from master.dbo.sysmessages where error=@msgnum and msglangid=@msglangid) > 0
  2052.     if lower(@replace) = 'replace'
  2053.         begin
  2054.             delete from master.dbo.sysmessages where error = @msgnum and msglangid = @msglangid
  2055.             /*
  2056.             ** If we're REPLACEing a us_english message, make sure any non-us_english messages get updated with the same severity
  2057.             */
  2058.             if (@langid = 0)
  2059.                 begin
  2060.                     update master.dbo.sysmessages set severity = @severity
  2061.                     where error = @msgnum and msglangid <> 1033
  2062.                 end
  2063.         end
  2064.     else
  2065.         begin
  2066.             /*
  2067.             ** The 'replace' option wasn't specified and a
  2068.             ** msg. with the number already exists.
  2069.             */
  2070.             raiserror(15043,-1,-1)
  2071.             return(1)
  2072.         end
  2073.  
  2074. /*
  2075. **  Create the message.
  2076. */
  2077. insert into master.dbo.sysmessages(error,severity,description,dlevel,msglangid)
  2078.     values (@msgnum,@severity,@msgtext,@dlevel,@msglangid)
  2079.  
  2080.  
  2081. return (0) -- sp_addmessage
  2082. go
  2083.  
  2084.  
  2085.  
  2086. raiserror(15339,-1,-1,'sp_addumpdevice')
  2087. go
  2088. create procedure sp_addumpdevice -- 1995/09/07 12:01
  2089. @devtype varchar(20),      /* disk, tape, or diskette */
  2090. @logicalname   sysname,      /* logical name of the device */
  2091. @physicalname  nvarchar(260),     /* physical name of the device */
  2092. @cntrltype  smallint = null,  /* controller type - ignored. */
  2093. @devstatus  varchar(40) = 'noskip'  /* device characteristics */
  2094. as
  2095.  
  2096. declare @status smallint      /* status bits for device */
  2097. declare @returncode int
  2098.  
  2099. /*
  2100. **  An open txn might jeopardize a recovery.
  2101. */
  2102. set implicit_transactions off
  2103. if @@trancount > 0
  2104.    begin
  2105.       raiserror(15002,-1,-1,'sp_addumpdevice')
  2106.       return (1)
  2107.    end
  2108.  
  2109. /*
  2110. **  You must be SA to execute this sproc.
  2111. */
  2112. if (not is_srvrolemember('diskadmin') = 1)
  2113.    begin
  2114.       raiserror(15247,-1,-1)
  2115.       return (1)
  2116.    end
  2117.  
  2118. select @devtype=lower(@devtype)
  2119.  
  2120. /*
  2121. **  Check out the @devtype.
  2122. */
  2123. if @devtype not in ('disk', 'tape', 'diskette', 'pipe', 'virtual_device')
  2124.    begin
  2125.       raiserror(15044,-1,-1,@devtype)
  2126.       return (1)
  2127.    end
  2128.  
  2129. /*
  2130. **  Check the args are not NULL.
  2131. */
  2132. if @logicalname is null
  2133.    begin
  2134.       raiserror(15045,-1,-1)
  2135.       return(1)
  2136.    end
  2137.  
  2138. /*
  2139. **  Check to see that the @logicalname is valid.
  2140. */
  2141. exec @returncode = sp_validname @logicalname
  2142. if @returncode <> 0
  2143.    return(1)
  2144.  
  2145. if @physicalname is null
  2146.    begin
  2147.       raiserror(15046,-1,-1)
  2148.       return(1)
  2149.    end
  2150.  
  2151. /*
  2152. **  Make sure physical file name would be unique among devices.
  2153. */
  2154. if exists (select * from master.dbo.sysdevices where phyname = @physicalname)
  2155.    begin
  2156.       raiserror(15061,-1,-1,@physicalname)
  2157.       return (1)
  2158.    end
  2159.  
  2160. /*
  2161. **  Prohibit certain special english words from being logical names.
  2162. */
  2163. if (@logicalname IN ('disk' ,'diskette' ,'tape' ,'floppy'))
  2164.    begin
  2165.       raiserror(15285,-1,-1,@logicalname)
  2166.       return (1)
  2167.    end
  2168.  
  2169. /*
  2170. **  Make sure that a device with @logicalname doesn't already exist.
  2171. */
  2172. if exists (select * from master.dbo.sysdevices where name = @logicalname)
  2173.    begin
  2174.       raiserror(15026,-1,-1,@logicalname)
  2175.       return (1)
  2176.    end
  2177.  
  2178. /*
  2179. **  Always turn on the dump status bit.
  2180. */
  2181. select @status = 16
  2182.  
  2183. /*
  2184. **  If @devtype is a tape then check to see if devstatus is 'skip'.
  2185. */
  2186. if @devtype = 'tape'
  2187.    begin
  2188.       if @devstatus not in ('noskip','skip')
  2189.          begin
  2190.             raiserror(15047,-1,-1)
  2191.             return (1)
  2192.          end
  2193.  
  2194.       if @devstatus = 'skip' select @status = @status | 8
  2195.    end
  2196.  
  2197. /*
  2198. **  If a disk then the cntrltype = 2
  2199. */
  2200. if @devtype = 'disk'
  2201.    begin
  2202.       insert into master.dbo.sysdevices
  2203.          (low, high, size, status, cntrltype, name, phyname)
  2204.          values
  2205.          (0, 0, 0, @status, 2, @logicalname, @physicalname)
  2206.       raiserror(15444,-1,-1)
  2207.    end
  2208.  
  2209. /*
  2210. **  If a diskette then the cntrltype in (3,4)
  2211. */
  2212. if @devtype = 'diskette'
  2213.    begin
  2214.       insert into master.dbo.sysdevices
  2215.          (low, high, size, status, cntrltype, name, phyname)
  2216.          values
  2217.          (0, 0, 0, @status, 3, @logicalname, @physicalname)
  2218.       raiserror(15445,-1,-1)
  2219.    end
  2220.  
  2221. /*
  2222. **  Tape device.
  2223. */
  2224. if @devtype = 'tape'
  2225.    begin
  2226.       insert into master.dbo.sysdevices
  2227.          (low, high, size, status, cntrltype, name, phyname)
  2228.          values
  2229.          (0, 0, 0, @status, 5, @logicalname,@physicalname)
  2230.       raiserror(15446,-1,-1)
  2231.    end
  2232.  
  2233. /*
  2234. ** Pipe.
  2235. */
  2236. if @devtype = 'pipe'
  2237.    begin
  2238.       insert into master.dbo.sysdevices
  2239.          (low, high, size, status, cntrltype, name, phyname)
  2240.          values
  2241.          (0, 0, 0, @status, 6, @logicalname,@physicalname)
  2242.       raiserror(15447,-1,-1)
  2243.    end
  2244.  
  2245. /*
  2246. ** Virtual device.
  2247. */
  2248. if @devtype = 'virtual_device'
  2249.    begin
  2250.       insert into master.dbo.sysdevices
  2251.          (low, high, size, status, cntrltype, name, phyname)
  2252.          values
  2253.          (0, 0, 0, @status, 7, @logicalname,@physicalname)
  2254.       raiserror(15031,-1,-1)
  2255.    end
  2256.  
  2257.  
  2258. return (0) -- sp_addumpdevice
  2259. go
  2260.  
  2261.  
  2262. raiserror(15339,-1,-1,'sp_addremotelogin')
  2263. go
  2264. create procedure sp_addremotelogin --- 1996/04/08 00:00
  2265.     @remoteserver    sysname,        /* name of remote server */
  2266.     @loginame       sysname = NULL,        /* user's remote name */
  2267.     @remotename     sysname = NULL        /* user's local user name */
  2268. as
  2269.     declare @srvid smallint
  2270.     declare @sid varbinary(85)
  2271.  
  2272.     -- DISALLOW USER XACT --
  2273.     set implicit_transactions off
  2274.     if @@trancount > 0
  2275.     begin
  2276.         raiserror(15002,-1,-1,'sp_addremotelogin')
  2277.         return (1)
  2278.     end
  2279.  
  2280.     -- CHECK PERMISSIONS
  2281.     if not (is_srvrolemember('securityadmin') = 1)
  2282.     begin
  2283.         raiserror(15247,-1,-1)
  2284.         return (1)
  2285.     end
  2286.  
  2287.     -- VALIDATE SERVER NAME --
  2288.     select @srvid = srvid from master.dbo.sysservers where srvname = @remoteserver
  2289.     if @srvid is null
  2290.     begin
  2291.         raiserror(15015,-1,-1,@remoteserver)
  2292.         return (1)
  2293.     end
  2294.  
  2295.     -- CHECK FOR INVALID PARAMETER SYNTAX --
  2296.     if @loginame is null and @remotename is not null
  2297.     begin
  2298.         raiserror(15600,-1,-1,'sp_addremotelogin')
  2299.         return (1)
  2300.     end
  2301.  
  2302.     -- VALIDATE @loginame --
  2303.     if @loginame is not null
  2304.     begin
  2305.         select @sid = sid from master.dbo.syslogins where loginname = @loginame
  2306.                     AND isntname = 0        -- cannot remap to NT login
  2307.         if @sid is null
  2308.         begin
  2309.             raiserror(15067,-1,-1,@loginame)
  2310.             return (1)
  2311.         end
  2312.     end
  2313.  
  2314.     -- CHECK FOR DUPLICATE <@remoteserver, @remotename> PAIR --
  2315.     --    (Note that this works for @remotename null and not null)
  2316.     if exists (select * from master.dbo.sysxlogins where srvid = @srvid
  2317.                 AND ((@remotename is null AND name is null) OR name = @remotename)
  2318.                 AND isrpcinmap = 1)
  2319.     begin
  2320.         if @remotename is null
  2321.             raiserror(15066,-1,-1,@remoteserver)
  2322.         else
  2323.             raiserror(15068,-1,-1,@remotename,@remoteserver)
  2324.         return (1)
  2325.     end
  2326.  
  2327.     -- Check if there is an outgoing mapping to which we can tag on this
  2328.     -- incoming mapping
  2329.     update master.dbo.sysxlogins set xstatus = xstatus | 32, xdate2 = getdate()
  2330.         where srvid = @srvid
  2331.         AND ((@remotename is null AND name is null) OR name = @remotename)
  2332.         AND ((@sid is null AND sid is null) OR sid = @sid)
  2333.  
  2334.     -- If update didnt happen, add an entry. (@srvid, @remotename, @sid)
  2335.     if @@rowcount = 0
  2336.         insert into master.dbo.sysxlogins
  2337.             values(@srvid, @sid, 32, getdate(), getdate(), @remotename, NULL, 0, NULL)
  2338.  
  2339.     -- SUCCESS --
  2340.     return (0)    -- sp_addremotelogin
  2341. go
  2342.  
  2343.  
  2344. checkpoint
  2345. go
  2346.  
  2347.  
  2348. raiserror(15339,-1,-1,'sp_addtype')
  2349. go
  2350. create procedure sp_addtype --- 1996/04/08 00:00
  2351. @typename sysname,        -- name of user-defined type
  2352. @phystype sysname,        -- physical system type of user-defined type
  2353. @nulltype varchar(8) = null,    -- nullability of new type
  2354. @owner sysname = null    -- Owner of type (default is caller)
  2355. as
  2356.  
  2357. declare @len int        -- length of user type
  2358. declare @type tinyint        -- typeid of physical type
  2359. declare @tlen smallint        -- length of physical type
  2360. declare @typeid smallint    -- user typeid of physical type
  2361. declare @nonull bit        -- default is getansinull()
  2362. declare @prec int        -- precision of the datatype
  2363. declare @scale int        -- scale of the datatype
  2364. declare @tprec tinyint        -- precision of the datatype read from systypes
  2365. declare @tscale tinyint        -- scale of the datatype read from systypes
  2366. declare @tname sysname  -- typename from systypes
  2367. declare @tstat tinyint      -- typestat from systypes
  2368. declare @orig_phystype    sysname
  2369. declare @default_collationid int        ----- default collation id
  2370. declare @collationid int            ---------collation id bo be used
  2371. select @orig_phystype = @phystype
  2372. select @nulltype = rtrim(lower(@nulltype))
  2373. select @typename = rtrim(@typename)
  2374. select @phystype = lower(rtrim(@phystype))
  2375.  
  2376. -- VALIDATE THE @owner NAME (and verify caller can use this name)
  2377. declare @uid smallint
  2378. if @owner is null
  2379.     select @uid = user_id()
  2380. else
  2381.     select @uid = uid from sysusers where name = @owner
  2382.         and isaliased = 0 AND uid NOT IN (0,3,4) --public/INFO_SCHEMA/etc can't own type
  2383. if @uid is null OR
  2384.     (is_member('db_owner')=0 AND
  2385.      is_member('db_ddladmin')=0 AND
  2386.      is_member(user_name(@uid))=0)
  2387. begin
  2388.     raiserror(15600, -1, -1, 'sp_addtype')
  2389.     return 1
  2390. end
  2391.  
  2392. -- TYPES BASED ON BIT CAN BE NULL IN SPHINX,
  2393. --    BUT MAKE NOT-NULL THE DFLT FOR BCKWRD-COMPAT
  2394. if lower(@phystype) = 'bit' and @nulltype is null
  2395.                 -- If user didn't specify nullability,
  2396.                 -- make sure it doesn't get set to nullable
  2397.                 -- by getansinull()
  2398.         select @nulltype = 'not null'
  2399.  
  2400. /*
  2401. **  Should the user type allow NULLs?
  2402. */
  2403. if @nulltype is null
  2404.     select @nonull = abs(getansinull()-1)
  2405. else if @nulltype = 'null'
  2406.     select @nonull = 0
  2407. else if @nulltype in ('not null','nonull')
  2408.     select @nonull = 1
  2409. else
  2410.     begin
  2411.         raiserror(15085,-1,-1)
  2412.         return (1)
  2413.     end
  2414.  
  2415. /*
  2416. **  Check to see that the @typename is valid.
  2417. */
  2418. declare @returncode int
  2419. execute @returncode = sp_validname @typename
  2420. if @returncode <> 0
  2421.     return(1)
  2422.  
  2423. /*
  2424. **  Check to see if the user type already exists or a system type
  2425. **  whose name = lower(@typename) (or a synomym) already exists.
  2426. */
  2427. if exists (select * from systypes where name = @typename
  2428.             or (name = lower(@typename) and xusertype <= 256))
  2429.         or lower(@typename)
  2430.         in ('character','character varying','char varying',
  2431.             'integer','dec','binary varying',
  2432.             'national character varying','national character',
  2433.             'national char varying','national char',
  2434.             'national text',
  2435.             'ncharacter varying', 'ncharacter', 'nchar varying',
  2436.             'rowversion')
  2437.     begin
  2438.         raiserror(15029,-1,-1,@typename)
  2439.         return (1)
  2440.     end
  2441.  
  2442. /*
  2443. **  Check to see if the user type has been reserved for future use.
  2444. */
  2445. if @typename in ('variant')
  2446.     begin
  2447.         raiserror(15075,-1,-1,@typename)
  2448.         return (1)
  2449.     end
  2450.  
  2451. /*
  2452. ** Can't supply length with sysname type.
  2453. */
  2454. if @phystype like 'sysname%(%'
  2455.     begin
  2456.         raiserror(15270,-1,-1)
  2457.         return(1)
  2458.     end
  2459.  
  2460. /*
  2461. ** initialize the length to be NULL first.
  2462. */
  2463. select @len = NULL
  2464.  
  2465. /*
  2466. ** If precision and scale were given with the type - extract them
  2467. */
  2468. if @phystype like '_%(_%,_%)'
  2469. begin
  2470.     select @prec = convert(int, substring(@phystype,
  2471.         charindex('(',@phystype) + 1,
  2472.         charindex(',',@phystype) - 1 - charindex('(',@phystype)))
  2473.  
  2474.     select @scale = convert(int, substring(@phystype,
  2475.         charindex(',',@phystype) + 1,
  2476.         charindex(')',@phystype) - 1 - charindex(',',@phystype)))
  2477.     /*
  2478.     ** Extract the physical type name
  2479.     */
  2480.     select @phystype = substring(@phystype, 1,
  2481.            charindex('(', @phystype) - 1)
  2482. end
  2483. else
  2484.  
  2485. /*
  2486. **  If a length was given with the user datatype, extract it.
  2487. */
  2488. if @phystype like '_%(%)'
  2489. begin
  2490.     select @len = convert(int, substring(@phystype,
  2491.         charindex('(',@phystype) + 1,
  2492.         charindex(')',@phystype) - 1 - charindex('(',@phystype)))
  2493.  
  2494.     /*
  2495.     ** Extract the physical type name
  2496.     */
  2497.     select @phystype = substring(@phystype, 1,
  2498.            charindex('(', @phystype) - 1)
  2499. end
  2500.  
  2501. select @phystype = rtrim(@phystype)
  2502.  
  2503. select @phystype= (case @phystype
  2504.     when 'character' then 'char'
  2505.     when 'character varying' then 'varchar'
  2506.     when 'char varying' then 'varchar'
  2507.     when 'integer' then 'int'
  2508.     when 'dec' then 'decimal'
  2509.     when 'binary varying' then 'varbinary'
  2510.     when 'national character varying' then 'nvarchar'
  2511.     when 'national char varying' then 'nvarchar'
  2512.     when 'national character' then 'nchar'
  2513.     when 'national char' then 'nchar'
  2514.     when 'ncharacter varying' then 'nvarchar'
  2515.     when 'ncharacter' then 'nchar'
  2516.     when 'nchar varying' then 'nvarchar'
  2517.     when 'national text' then 'ntext'
  2518.     when 'rowversion' then 'timestamp'
  2519.     else @phystype
  2520.     end)
  2521.  
  2522.  
  2523. /*
  2524. **  Make sure that the physical type exists and get its characteristics.
  2525. **  System physical types have a xusertype < 256 and are owned by the
  2526. **  dbo (userid = 1).
  2527. */
  2528. select @type = xtype, @tlen = length,
  2529.     @tprec = xprec, @tscale = xscale, @tstat = status, @tname = name
  2530. from systypes
  2531.     where xusertype < 256 and name = @phystype and uid = 1
  2532.  
  2533. if @type is null
  2534. begin
  2535.     raiserror(15036,-1,-1,@orig_phystype)
  2536.     return (1)
  2537. end
  2538.  
  2539. /*
  2540. ** get the default collation
  2541. */
  2542.  
  2543. select @default_collationid  = collationid from systypes where name = @tname
  2544.  
  2545. /*
  2546. **  Disallow user-defined datatypes on timestamps.  This is done because
  2547. **  a timestamp is not a basic type but is really a binary.  There is,
  2548. **  therefore, no way to tell if a user-defined datatype is mapped to
  2549. **  a binary or a timestamp.  Timestamps can't have rules or defaults.
  2550. */
  2551. if @phystype = 'timestamp'
  2552. begin
  2553.     raiserror(15038,-1,-1)
  2554.     return (1)
  2555. end
  2556.  
  2557. /*
  2558. **  Check if the NULL status of the user type is consistent with the NULL status
  2559. **  of the physical type.  Here are the possible cases.
  2560. **
  2561. **           physical type
  2562. **          NULLs      NONULLs
  2563. **            -----------------
  2564. ** user    NULLs    |  ok    |  no
  2565. ** type NONULLs    |  ok    |  ok
  2566. */
  2567. -- NOT NECESSARY: bit and timestamp both already special-cased
  2568. /**********
  2569. if @nonull = 0 and 1 = 0
  2570.     begin
  2571.         raiserror(15037,-1,-1,@orig_phystype)
  2572.         return (1)
  2573.     end
  2574. **********/
  2575.  
  2576. /* Decide about precision, scale, length
  2577. ** First check from NUMERIC, DECIMAL
  2578. */
  2579. if @tname in ('numeric','decimal')
  2580. begin
  2581.     /* Type is NUMERIC or DECIMAL */
  2582.  
  2583.     if @len > 0
  2584.         begin
  2585.             /* Length is really the precision
  2586.             ** Since no scale is specified then scale
  2587.             ** is minimum(Default, precision). Default = 4
  2588.             */
  2589.             select @prec = @len
  2590.             select @scale = 0
  2591.         end
  2592.     else
  2593.         if (@prec is NULL)
  2594.             begin
  2595.                 select @prec = 18
  2596.                 select @scale = 0
  2597.             end
  2598.  
  2599.     if (@prec > 38) or (@prec < 1)
  2600.         begin
  2601.             raiserror(15086,-1,-1)
  2602.             return (1)
  2603.         end
  2604.  
  2605.     if (@scale > @prec) or (@scale < 0)
  2606.         begin
  2607.             /*
  2608.             ** Illegal scale specified -- must be less than precision
  2609.             ** and positive.
  2610.             */
  2611.             raiserror(15087,-1,-1)
  2612.             return (1)
  2613.         end
  2614.  
  2615.     /* Compute length from precision */
  2616.     if (@prec <= 9)
  2617.         select @len = 5
  2618.  
  2619.     if (@prec > 9) and (@prec <= 19)
  2620.         select @len = 9
  2621.  
  2622.     if (@prec > 19) and (@prec <= 28)
  2623.         select @len = 13
  2624.  
  2625.     if (@prec > 28) and (@prec <= 38)
  2626.         select @len = 17
  2627.  
  2628. end
  2629. else
  2630.  
  2631. /*
  2632. **  Typeids 1 (char), 2 (varchar), 3 (binary) and 4 (varbinary) are the
  2633. **  only ones which allow a length to be specified.
  2634. */
  2635. if @tname not in ('binary', 'varbinary', 'char', 'varchar', 'nchar', 'nvarchar')
  2636.     begin
  2637.         /*
  2638.         **  We can't use a length and we got one.
  2639.         */
  2640.         if @len > 0
  2641.             begin
  2642.                 raiserror(15088,-1,-1)
  2643.                 return (1)
  2644.             end
  2645.  
  2646.         /*
  2647.         **  Use the fixed length of the physical type.
  2648.         */
  2649.         select @len = @tlen
  2650.         select @prec = @tprec
  2651.         select @scale = @tscale
  2652.     end
  2653. else
  2654.     begin
  2655.         /*
  2656.         **  We need a length and we didn't get one.
  2657.         */
  2658.         if @len is null
  2659.             begin
  2660.                 raiserror(15091,-1,-1)
  2661.                 return (1)
  2662.             end
  2663.  
  2664.         -- need to adjust length for unicode (watch out for overflow!)
  2665.         if @tname in ('nchar', 'nvarchar') and (@len & 0x80000000) != 0x80000000
  2666.             select @len = @len * 2
  2667.         if @len <= 0 or @len > 8000
  2668.             begin
  2669.                 raiserror(15092,-1,-1)
  2670.                 return (1)
  2671.             end
  2672.  
  2673.         select @prec = @tprec
  2674.         select @scale = @tscale
  2675.     end
  2676.  
  2677. /*
  2678. **Get the collation's id
  2679. */
  2680.  
  2681. if @tname  in ('char', 'nchar', 'ntext', 'nvarchar', 'text', 'varchar')
  2682.     begin
  2683.         select @collationid = @default_collationid
  2684.     end
  2685. else
  2686.     begin
  2687.         select @collationid=NULL
  2688.     end
  2689.  
  2690. /*
  2691. **  Finally, get the maximum existing user type so we use it + 1 for this
  2692. **  new type.
  2693. */
  2694. select @typeid = max(xusertype)
  2695.     from systypes
  2696.  
  2697. /*
  2698. **  There are no user defined types yet so use the first number (256).
  2699. */
  2700. if @typeid < 256
  2701.     select @typeid = 256
  2702.  
  2703. -- Set null status bit
  2704. if @nonull = 1
  2705.     select @tstat = @tstat | 0x01
  2706. else
  2707.     select @tstat = @tstat & 0xFE
  2708.  
  2709. insert systypes (name, xtype, status, xusertype, length, xprec, xscale,
  2710.             tdefault, domain, uid, reserved, collationid)
  2711.     select @typename, @type, @tstat, @typeid + 1, @len, @prec, @scale,
  2712.             0, 0, @uid, 0, @collationid
  2713.  
  2714. raiserror(15449,-1,-1)
  2715.  
  2716. return (0) -- sp_addtype
  2717. go
  2718.  
  2719.  
  2720. raiserror(15339,-1,-1,'sp_altermessage')
  2721. go
  2722. create procedure sp_altermessage --- 1996/04/08 00:00
  2723. @message_id       int,
  2724. @parameter        sysname,
  2725. @parameter_value  varchar(5)
  2726. as
  2727. begin
  2728.   declare @msg            varchar(128)
  2729.  
  2730.   select @parameter = upper(@parameter)
  2731.   select @parameter_value = upper(@parameter_value)
  2732.  
  2733.     -- Must be ServerAdmin to manage messages
  2734.     if is_srvrolemember('serveradmin') = 0
  2735.     begin
  2736.         raiserror(15247,-1,-1)
  2737.         return (1)
  2738.     end
  2739.  
  2740.   /*
  2741.   ** Does this message exist?
  2742.   */
  2743.   if (not exists (select * from master.dbo.sysmessages
  2744.                   where error = @message_id))
  2745.   begin
  2746.           raiserror(15179,-1,-1,@message_id)
  2747.           return (1)
  2748.   end
  2749.  
  2750.   /*
  2751.   ** Is Parameter 'WITH_LOG'?
  2752.   */
  2753.   if (@parameter <> 'WITH_LOG')
  2754.   begin
  2755.     raiserror(15176,-1,-1)
  2756.     return (1)
  2757.   end
  2758.  
  2759.   /*
  2760.   ** Is ParameterValue TRUE or FALSE?
  2761.   */
  2762.   if (@parameter_value not in ('TRUE', 'FALSE'))
  2763.   begin
  2764.           raiserror(15277,-1,-1)
  2765.           return (1)
  2766.   end
  2767.  
  2768.  
  2769.   /*
  2770.   ** Turn dlevel bit 7 on or off
  2771.   */
  2772.   if (@parameter_value = 'TRUE')
  2773.   begin
  2774.           update master.dbo.sysmessages
  2775.                   set dlevel = dlevel | 0x80
  2776.                           where error = @message_id
  2777.   end
  2778.   else
  2779.   if (@parameter_value = 'FALSE')
  2780.   begin
  2781.           update master.dbo.sysmessages
  2782.                   set dlevel = dlevel & 0x7FFFFF7F
  2783.                           where error = @message_id
  2784.   end
  2785.   return (0)
  2786. end
  2787. -- sp_altermessage
  2788. go
  2789.  
  2790. raiserror(15339,-1,-1,'sp_attach_db')
  2791. go
  2792. create procedure sp_attach_db
  2793. @dbname sysname
  2794. , @filename1 nvarchar(260)
  2795. , @filename2 nvarchar(260) = NULL
  2796. , @filename3 nvarchar(260) = NULL
  2797. , @filename4 nvarchar(260) = NULL
  2798. , @filename5 nvarchar(260) = NULL
  2799. , @filename6 nvarchar(260) = NULL
  2800. , @filename7 nvarchar(260) = NULL
  2801. , @filename8 nvarchar(260) = NULL
  2802. , @filename9 nvarchar(260) = NULL
  2803. , @filename10 nvarchar(260) = NULL
  2804. , @filename11 nvarchar(260) = NULL
  2805. , @filename12 nvarchar(260) = NULL
  2806. , @filename13 nvarchar(260) = NULL
  2807. , @filename14 nvarchar(260) = NULL
  2808. , @filename15 nvarchar(260) = NULL
  2809. , @filename16 nvarchar(260) = NULL
  2810. as
  2811. declare @execstring nvarchar (4000)
  2812. set nocount on
  2813.  
  2814.     IF ((@dbname is null OR datalength(@dbname) = 0) OR
  2815.         (@filename1 is null OR datalength(@filename1) = 0))
  2816.     begin
  2817.         raiserror (15004,-1,-1)
  2818.         return (1)
  2819.     end
  2820.  
  2821.     -- build initial CREATE DATABASE
  2822.     select @execstring = 'CREATE DATABASE '
  2823.         + quotename( @dbname , '[')
  2824.         + ' ON (FILENAME ='
  2825.         + ''''
  2826.         + REPLACE(@filename1,N'''',N'''''')
  2827.         + ''''
  2828.  
  2829.     -- add any additional files
  2830.  
  2831.     if (@filename2 IS NOT NULL)
  2832.     begin
  2833.         select @execstring = @execstring
  2834.             + ' ), (FILENAME= '''
  2835.             + REPLACE(@filename2 ,N'''',N'''''')
  2836.             + ''''
  2837.     end
  2838.  
  2839.     if (@filename3 IS NOT NULL)
  2840.     begin
  2841.         select @execstring = @execstring
  2842.             + ' ), (FILENAME= '''
  2843.             + REPLACE(@filename3 ,N'''',N'''''')
  2844.             + ''''
  2845.     end
  2846.  
  2847.     if (@filename4 IS NOT NULL)
  2848.     begin
  2849.         select @execstring = @execstring
  2850.             + ' ), (FILENAME= '''
  2851.             + REPLACE(@filename4 ,N'''',N'''''')
  2852.             + ''''
  2853.     end
  2854.  
  2855.     if (@filename5 IS NOT NULL)
  2856.     begin
  2857.         select @execstring = @execstring
  2858.             + ' ), (FILENAME= '''
  2859.             + REPLACE(@filename5 ,N'''',N'''''')
  2860.             + ''''
  2861.     end
  2862.  
  2863.     if (@filename6 IS NOT NULL)
  2864.     begin
  2865.         select @execstring = @execstring
  2866.             + ' ), (FILENAME= '''
  2867.             + REPLACE(@filename6 ,N'''',N'''''')
  2868.             + ''''
  2869.     end
  2870.  
  2871.     if (@filename7 IS NOT NULL)
  2872.     begin
  2873.         select @execstring = @execstring
  2874.             + ' ), (FILENAME= '''
  2875.             + REPLACE(@filename7 ,N'''',N'''''')
  2876.             + ''''
  2877.     end
  2878.  
  2879.     if (@filename8 IS NOT NULL)
  2880.     begin
  2881.         select @execstring = @execstring
  2882.             + ' ), (FILENAME= '''
  2883.             + REPLACE(@filename8  ,N'''',N'''''')
  2884.             + ''''
  2885.     end
  2886.  
  2887.     if (@filename9 IS NOT NULL)
  2888.     begin
  2889.         select @execstring = @execstring
  2890.             + ' ), (FILENAME= '''
  2891.             + REPLACE(@filename9 ,N'''',N'''''')
  2892.             + ''''
  2893.     end
  2894.  
  2895.     if (@filename10 IS NOT NULL)
  2896.     begin
  2897.         select @execstring = @execstring
  2898.             + ' ), (FILENAME= '''
  2899.             + REPLACE(@filename10  ,N'''',N'''''')
  2900.             + ''''
  2901.     end
  2902.  
  2903.     if (@filename11 IS NOT NULL)
  2904.     begin
  2905.         select @execstring = @execstring
  2906.             + ' ), (FILENAME= '''
  2907.             + REPLACE(@filename11  ,N'''',N'''''')
  2908.             + ''''
  2909.     end
  2910.  
  2911.     if (@filename12 IS NOT NULL)
  2912.     begin
  2913.         select @execstring = @execstring
  2914.             + ' ), (FILENAME= '''
  2915.             + REPLACE(@filename12  ,N'''',N'''''')
  2916.             + ''''
  2917.     end
  2918.  
  2919.     if (@filename13 IS NOT NULL)
  2920.     begin
  2921.         select @execstring = @execstring
  2922.             + ' ), (FILENAME= '''
  2923.             + REPLACE(@filename13  ,N'''',N'''''')
  2924.             + ''''
  2925.     end
  2926.  
  2927.     if (@filename14 IS NOT NULL)
  2928.     begin
  2929.         select @execstring = @execstring
  2930.             + ' ), (FILENAME= '''
  2931.             + REPLACE(@filename14  ,N'''',N'''''')
  2932.             + ''''
  2933.     end
  2934.  
  2935.     if (@filename15 IS NOT NULL)
  2936.     begin
  2937.         select @execstring = @execstring
  2938.             + ' ), (FILENAME= '''
  2939.             + REPLACE(@filename15 ,N'''',N'''''')
  2940.             + ''''
  2941.     end
  2942.  
  2943.     if (@filename16 IS NOT NULL)
  2944.     begin
  2945.         select @execstring = @execstring
  2946.             + ' ), (FILENAME= '''
  2947.             + REPLACE(@filename16  ,N'''',N'''''')
  2948.             + ''''
  2949.     end
  2950.  
  2951.  
  2952.     -- note it as for attach
  2953.     select @execstring = @execstring + ' ) FOR ATTACH'
  2954.     exec (@execstring)
  2955.  
  2956. if @@error <>  0
  2957.     begin
  2958.         -- No need to raiserror as the CREATE DATABASE will do so
  2959.         return(1)
  2960.     end
  2961. return (0) -- sp_attach_db
  2962. go
  2963.  
  2964.  
  2965. raiserror(15339,-1,-1,'sp_attach_single_file_db')
  2966. go
  2967. create procedure sp_attach_single_file_db
  2968. @dbname sysname,
  2969. @physname nvarchar(260)
  2970. as
  2971. declare @execstring nvarchar (400)
  2972. set nocount on
  2973.     IF ((@dbname is null OR datalength(@dbname) = 0) OR
  2974.        (@physname is null OR datalength(@physname) = 0))
  2975.     begin
  2976.         raiserror (15004,-1,-1)
  2977.         return (1)
  2978.     end
  2979.  
  2980.     select @execstring = 'CREATE DATABASE '
  2981.         + quotename( @dbname , '[')
  2982.         + ' ON (FILENAME ='
  2983.         + ''''
  2984.         + REPLACE(@physname,N'''',N'''''')
  2985.         + ''''
  2986.         + ' ) FOR ATTACH'
  2987.     exec (@execstring)
  2988. if @@error <>  0
  2989.     begin
  2990.         -- No need to raiserror as the CREATE DATABASE will do so
  2991.         return(1)
  2992.     end
  2993.     -- strip out replication from this database
  2994. if exists (select * from master.dbo.sysobjects where name=N'sp_removedbreplication')
  2995.     begin
  2996.         exec sp_removedbreplication @dbname
  2997.     end
  2998.     return (0) -- sp_attach_single_file_db
  2999. go
  3000.  
  3001.  
  3002. raiserror(15339,-1,-1,'sp_helplanguage')
  3003. go
  3004. create procedure sp_helplanguage --- 1996/04/08 00:00
  3005. @language sysname = NULL
  3006. as
  3007.  
  3008. /* Print all languages if the user didn't give the language name. */
  3009. if @language is null
  3010. begin
  3011.     if exists (select * from master.dbo.syslanguages)
  3012.         select * from master.dbo.syslanguages
  3013.     else
  3014.         raiserror(15452,-1,-1)
  3015.  
  3016.     /* Find out whether us_english is there or not. */
  3017.     if not exists (select * from master.dbo.syslanguages
  3018.             where name = 'us_english')
  3019.         raiserror(15453,-1,-1)
  3020.  
  3021.     return (0)
  3022. end
  3023.  
  3024. /*  Report information on this language. */
  3025. if exists (select * from master.dbo.syslanguages where name = @language)
  3026.     begin
  3027.         select * from master.dbo.syslanguages where name = @language
  3028.         return (0)
  3029.     end
  3030.  
  3031. if exists (select * from master.dbo.syslanguages where alias = @language)
  3032.     begin
  3033.         select * from master.dbo.syslanguages where alias = @language
  3034.         return (0)
  3035.     end
  3036.  
  3037. /* Couldn't find this language. */
  3038. if @language = 'us_english'
  3039.     begin
  3040.         raiserror(15453,-1,-1)
  3041.         return (0)
  3042.     end
  3043. else
  3044.     begin
  3045.         raiserror(15033,-1,-1,@language)
  3046.         return (1)
  3047.     end
  3048. -- sp_helplanguage
  3049. go
  3050.  
  3051.  
  3052.  
  3053.  
  3054. checkpoint
  3055. go
  3056.  
  3057. raiserror(15339,-1,-1,'sp_bindefault')
  3058. go
  3059. create procedure sp_bindefault --- 1996/08/30 20:04
  3060. @defname nvarchar(776),            /* name of the default */
  3061. @objname nvarchar(517),            /* table or usertype name */
  3062. @futureonly varchar(15) = NULL        /* flag to indicate extent of binding */
  3063. as
  3064.  
  3065. declare @defid int            /* id of the default to bind */
  3066. declare @futurevalue varchar(15)    /* the value of @futureonly that causes
  3067.                     ** the binding to be limited */
  3068. declare
  3069.     @vc1            nvarchar(517)
  3070.     ,@tab_id        integer
  3071.     ,@parent_obj    integer
  3072.     ,@cur_tab_id    integer
  3073.     ,@colid            smallint
  3074.     ,@xtype            tinyint
  3075.     ,@xusertype        smallint
  3076.     ,@col_status    tinyint
  3077.     ,@col_default int
  3078.     ,@identity binary(1)
  3079.  
  3080. declare
  3081.     @UnqualDef            sysname
  3082.     ,@QualDef1            sysname
  3083.     ,@QualDef2            sysname
  3084.     ,@QualDef3            sysname
  3085.  
  3086.     ,@UnqualObj            sysname
  3087.     ,@QualObj1            sysname
  3088.     ,@QualObj2            sysname
  3089.     ,@QualObj3            sysname
  3090.  
  3091. set cursor_close_on_commit    off
  3092. set nocount            on
  3093.  
  3094. select @futurevalue = 'futureonly'    /* initialize @futurevalue */
  3095. select @identity = 0X80 /* identity columns*/
  3096.  
  3097. /*
  3098. **  When a default or rule is bound to a user-defined datatype, it is also
  3099. **  bound, by default, to any columns of the user datatype that are currently
  3100. **  using the existing default or rule as their default or rule.  This default
  3101. **  action may be overridden by setting @futureonly = @futurevalue when the
  3102. **  procedure is invoked.  In this case existing columns with the user
  3103. **  datatype won't have their existing default or rule changed.
  3104. */
  3105.  
  3106. -- get name parts --
  3107. select @UnqualDef = parsename(@defname, 1),
  3108.         @QualDef1 = parsename(@defname, 2),
  3109.         @QualDef2 = parsename(@defname, 3),
  3110.         @QualDef3 = parsename(@defname, 4)
  3111.  
  3112. select @UnqualObj = parsename(@objname, 1),
  3113.         @QualObj1 = parsename(@objname, 2),
  3114.         @QualObj2 = parsename(@objname, 3),
  3115.         @QualObj3 = parsename(@objname, 4)
  3116.  
  3117. IF (@UnqualDef is NULL OR @QualDef3 is not null)
  3118.    begin
  3119.    raiserror(15253,-1,-1,@defname)
  3120.    return (1)
  3121.    end
  3122.  
  3123. IF (@UnqualObj is NULL OR @QualObj3 is not null)
  3124.    begin
  3125.    raiserror(15253,-1,-1,@objname)
  3126.    return (1)
  3127.    end
  3128.  
  3129.  
  3130. ------------------  Verify database.
  3131.  
  3132. if ((@QualObj2 is not null and @QualObj1 is null)
  3133.     or (@QualDef2 is not null and @QualDef2 <> db_name()))
  3134.     begin
  3135.         raiserror(15076,-1,-1)
  3136.         return (1)
  3137.     end
  3138.  
  3139. /*
  3140. **  Check that the @futureonly argument, if supplied, is correct.
  3141. */
  3142. if (@futureonly IS NOT NULL)
  3143. begin
  3144.     select @futureonly = lower(@futureonly)
  3145.     if (@futureonly <> @futurevalue)
  3146.         begin
  3147.             raiserror(15100,-1,-1)
  3148.             return (1)
  3149.         end
  3150. end
  3151.  
  3152. /*
  3153. **  Check to see that the default exists and get its id.
  3154. */
  3155. select @defid = id, @parent_obj = parent_obj from sysobjects
  3156.             where id = object_id(@defname)
  3157.                 and xtype='D '    -- default object 6
  3158.  
  3159. if @defid is NULL
  3160.     begin
  3161.         raiserror(15016,-1,-1,@UnqualDef)
  3162.         return (1)
  3163.     end
  3164.  
  3165.  
  3166. if @parent_obj > 0
  3167.     begin
  3168.         raiserror(15050,-1,-1,@defname)
  3169.         return(1)
  3170.     end
  3171.  
  3172. /*
  3173. **  If @objname is of the form tab.col then we are binding to a column.
  3174. **  Otherwise its a datatype.  In the column case, we need to extract
  3175. **  and verify the table and column names and make sure the user owns
  3176. **  the table that is getting the default bound. We also need to ensure
  3177. **  that we don't overwrite any DRI style defaults.
  3178. */
  3179. if @QualObj1 is not null
  3180. begin
  3181.     if (@QualObj2 is not null)
  3182.         select @vc1 = QuoteName(@QualObj2) + '.' + QuoteName(@QualObj1)
  3183.     else
  3184.         select @vc1 = QuoteName(@QualObj1)
  3185.  
  3186.     select    @tab_id = o.id,        @colid = c.colid,
  3187.             @xtype = c.xtype,    @col_status = c.status,
  3188.             @col_default = c.cdefault
  3189.     from sysobjects o, syscolumns c
  3190.     where c.id = object_id(@vc1,'local')
  3191.             and c.name = @UnqualObj
  3192.             and o.id = c.id
  3193.             and o.xtype='U '
  3194.  
  3195.     /*Check that table and column exist*/
  3196.      if @tab_id is null
  3197.     begin
  3198.         raiserror(15104,-1,-1,@QualObj1,@UnqualObj)
  3199.         return (1)
  3200.     end
  3201.  
  3202.     /*
  3203.     **  If the column type is timestamp, disallow the bind.
  3204.     **  Defaults can't be bound to timestamp columns.
  3205.     */
  3206.     if type_name(@xtype) = 'timestamp'
  3207.     begin
  3208.         raiserror(15101,-1,-1)
  3209.         return (1)
  3210.     end
  3211.  
  3212.     /*
  3213.     **  If the column category is identity, disallow the bind.
  3214.     **  Defaults can't be bound to identity columns.
  3215.     */
  3216.     if @col_status & @identity = @identity
  3217.     begin
  3218.         raiserror(15102,-1,-1)
  3219.         return (1)
  3220.     end
  3221.  
  3222.    /*
  3223.    **  Check to see if the column was created with or altered
  3224.    **  to have a DRI style default value.
  3225.    */
  3226.     if @col_default > 0
  3227.         if exists
  3228.          (select    *
  3229.             from    sysobjects o
  3230.             where    @col_default       = o.id
  3231.             and        @tab_id             = o.parent_obj)
  3232.         begin
  3233.             raiserror(15103,-1,-1)
  3234.             return (1)
  3235.         end
  3236.  
  3237.     BEGIN TRANSACTION txn_bindefault_1
  3238.  
  3239.         /*
  3240.         **  Since binding a default is a schema change, update schema count
  3241.         **  for the object in the sysobjects table.
  3242.         */
  3243.  
  3244.         dbcc LockObjectSchema(@vc1) --- Undocu. Locks out other schema changes until commit, and increments sysobjects.schema_ver.
  3245.  
  3246.         update syscolumns set cdefault = @defid where id = @tab_id and colid = @colid
  3247.  
  3248.     COMMIT TRANSACTION txn_bindefault_1
  3249.  
  3250.     raiserror(15511,-1,-1)
  3251.  
  3252. end
  3253. else
  3254. begin
  3255.     /*
  3256.     **  We're binding to a user type.  In this case, the @objname
  3257.     **  is really the name of the user datatype.
  3258.     **  When we bind to a user type, any existing columns get changed
  3259.     **  to the new binding unless their current binding is not equal
  3260.     **  to the current binding for the usertype or if they set the
  3261.     **  @futureonly parameter to @futurevalue.
  3262.     */
  3263.     declare @olddefault int    /* current default for type */
  3264.  
  3265.     /*
  3266.     **  Get the current default for the datatype.
  3267.     */
  3268.  
  3269.     select @xusertype = xusertype, @olddefault = tdefault
  3270.         from systypes where name = @UnqualObj and xusertype > 256
  3271.         AND (is_member('db_owner') = 1 OR is_member('db_ddladmin') = 1 OR is_member(user_name(uid))=1)
  3272.  
  3273.     if @xusertype is null
  3274.         begin
  3275.             raiserror(15105,-1,-1)
  3276.             return (1)
  3277.         end
  3278.  
  3279.     update systypes
  3280.         set tdefault = @defid
  3281.             from systypes
  3282.         where xusertype = @xusertype
  3283.  
  3284.  
  3285.     raiserror(15512,-1,-1)
  3286.  
  3287.     /*
  3288.     **  need the new binding.
  3289.     */
  3290.     if isnull(@futureonly, ' ') <> @futurevalue
  3291.     begin
  3292.  
  3293.         declare ms_crs_t1 cursor local static for
  3294.           select
  3295.             distinct
  3296.                  c.id
  3297.                  ,c.colid
  3298.             from     syscolumns    c JOIN sysobjects o ON c.id = o.id AND o.xtype = N'U '
  3299.             where     c.xusertype    = @xusertype
  3300.             and    (c.cdefault    = @olddefault    OR
  3301.                  c.cdefault    = 0
  3302.                 )
  3303.             order by c.id
  3304.                   for read only
  3305.  
  3306.         open ms_crs_t1
  3307.  
  3308.         BEGIN TRANSACTION txn_bindefault_3
  3309.  
  3310.         fetch next from ms_crs_t1 into
  3311.              @tab_id,
  3312.              @colid
  3313.  
  3314.         WHILE @@fetch_status = 0
  3315.         begin
  3316.  
  3317.             select @vc1 = quotename(user_name(OBJECTPROPERTY(@tab_id,'OwnerId'))) + '.'
  3318.                         + quotename(object_name(@tab_id))
  3319.  
  3320.             dbcc LockObjectSchema(@vc1) --- Undocu. Locks out other schema changes until commit, and increments sysobjects.schema_ver.
  3321.  
  3322.             select @cur_tab_id = @tab_id
  3323.  
  3324.             while @cur_tab_id = @tab_id and @@fetch_status = 0
  3325.             begin
  3326.  
  3327.                 update syscolumns
  3328.                 set cdefault = @defid
  3329.                 from syscolumns c
  3330.                 where c.id = @tab_id
  3331.                 and c.colid = @colid
  3332.  
  3333.                 fetch next from ms_crs_t1 into
  3334.                      @tab_id,
  3335.                      @colid
  3336.             end
  3337.  
  3338.         end --loop 3
  3339.  
  3340.         COMMIT TRANSACTION txn_bindefault_3
  3341.  
  3342.         deallocate ms_crs_t1
  3343.  
  3344.         raiserror(15513,-1,-1)
  3345.     end
  3346. end
  3347.  
  3348. return (0) -- sp_bindefault
  3349. go
  3350.  
  3351. raiserror(15339,-1,-1,'sp_bindrule')
  3352. go
  3353. create procedure sp_bindrule --- 1996/08/14 15:02
  3354. @rulename nvarchar(776),            /* name of the rule */
  3355. @objname nvarchar(517),            /* table or usertype name */
  3356. @futureonly varchar(15) = NULL        /* column name */
  3357. as
  3358.  
  3359. declare @ruleid int            /* id of the rule to bind */
  3360. declare @futurevalue varchar(15)    /* the value of @futureonly that causes
  3361.                     ** the binding to be limited */
  3362.  
  3363. declare
  3364.     @vc1            nvarchar(517)
  3365.     ,@tab_id        integer
  3366.     ,@cur_tab_id    integer
  3367.     ,@colid            smallint
  3368.  
  3369.     ,@xtype            smallint
  3370.     ,@xusertype        smallint
  3371.  
  3372. declare
  3373.     @UnqualRule        sysname
  3374.     ,@QualRule1        sysname
  3375.     ,@QualRule2        sysname
  3376.     ,@QualRule3        sysname
  3377.  
  3378.     ,@UnqualObj        sysname
  3379.     ,@QualObj1        sysname
  3380.     ,@QualObj2        sysname
  3381.     ,@QualObj3        sysname
  3382.  
  3383. set cursor_close_on_commit    off
  3384. set nocount on
  3385.  
  3386. select @futurevalue = 'futureonly'    /* initialize @futurevalue */
  3387.  
  3388. /*
  3389. **  When a default or rule is bound to a user-defined datatype, it is also
  3390. **  bound, by default, to any columns of the user datatype that are currently
  3391. **  using the existing default or rule as their default or rule.  This default
  3392. **  action may be overridden by setting @futureonly = @futurevalue when the
  3393. **  procedure is invoked.  In this case existing columns with the user
  3394. **  datatype won't have their existing default or rule changed.
  3395. */
  3396.  
  3397. -- get name parts --
  3398. select @UnqualRule = parsename(@rulename, 1),
  3399.         @QualRule1 = parsename(@rulename, 2),
  3400.         @QualRule2 = parsename(@rulename, 3),
  3401.         @QualRule3 = parsename(@rulename, 4)
  3402.  
  3403. select @UnqualObj = parsename(@objname, 1),
  3404.         @QualObj1 = parsename(@objname, 2),
  3405.         @QualObj2 = parsename(@objname, 3),
  3406.         @QualObj3 = parsename(@objname, 4)
  3407.  
  3408. IF (@UnqualRule is NULL OR @QualRule3 is not null)
  3409.    begin
  3410.    raiserror(15253,-1,-1,@rulename)
  3411.    return (1)
  3412.    end
  3413.  
  3414. IF (@UnqualObj is NULL OR @QualObj3 is not null)
  3415.    begin
  3416.    raiserror(15253,-1,-1,@objname)
  3417.    return (1)
  3418.    end
  3419.  
  3420.  
  3421. ------------------  Verify database.
  3422.  
  3423. if ((@QualObj2 is not null and @QualObj1 is null)
  3424.     or (@QualRule2 is not null and @QualRule2 <> db_name()))
  3425.     begin
  3426.         raiserror(15077,-1,-1)
  3427.         return (1)
  3428.     end
  3429.  
  3430. /*
  3431. **  Check that the @futureonly argument, if supplied, is correct.
  3432. */
  3433. if (@futureonly IS NOT NULL)
  3434. begin
  3435.     select @futureonly = lower(@futureonly)
  3436.     begin
  3437.         if (@futureonly <> @futurevalue)
  3438.             begin
  3439.                 raiserror(15106,-1,-1)
  3440.                 return (1)
  3441.             end
  3442.     end
  3443. end
  3444.  
  3445. /*
  3446. **  Check to see that the rule exists and get its id.
  3447. */
  3448. select @ruleid = id from sysobjects
  3449.             where id = object_id(@rulename)
  3450.                 and xtype='R ' --rule object 7
  3451.  
  3452. if @ruleid is NULL
  3453.     begin
  3454.         raiserror(15017,-1,-1,@rulename)
  3455.         return (1)
  3456.     end
  3457.  
  3458. /*
  3459. **  If @objname is of the form tab.col then we are binding to a column.
  3460. **  Otherwise its a datatype.  In the column case, we need to extract
  3461. **  and verify the table and column names and make sure the user owns
  3462. **  the table that is getting the rule bound.
  3463. */
  3464. if @QualObj1 is not null
  3465. begin
  3466.     if (@QualObj2 is not null)
  3467.         select @vc1 = QuoteName(@QualObj2) + '.' + QuoteName(@QualObj1)
  3468.     else
  3469.         select @vc1 = QuoteName(@QualObj1)
  3470.  
  3471.     select @tab_id = o.id, @colid = c.colid, @xtype = c.xtype
  3472.     from sysobjects o, syscolumns c
  3473.     where c.id = object_id(@vc1,'local')
  3474.             and c.name = @UnqualObj
  3475.             and o.id = c.id
  3476.             and o.xtype='U '
  3477.  
  3478.     /*Check that table and column exist*/
  3479.      if @tab_id is null
  3480.     begin
  3481.         raiserror(15104,-1,-1,@QualObj1,@UnqualObj)
  3482.         return (1)
  3483.     end
  3484.  
  3485.     /*
  3486.     **  If the column type is image, text, or timestamp, disallow the bind.
  3487.     **  Rules can't be bound to image, text, or timestamp columns.
  3488.     **  The types are checked in case
  3489.     **  there is a user-defined datatype that is an image or text.
  3490.     **  User-defined datatypes mapping to timestamp are not allowed
  3491.     **  by sp_addtype.
  3492.     */
  3493.     if type_name(@xtype) in ('text', 'ntext', 'image', 'timestamp')
  3494.         begin
  3495.             raiserror(15107,-1,-1)
  3496.             return (1)
  3497.         end
  3498.  
  3499.     BEGIN TRANSACTION txn_bindrule_1
  3500.  
  3501.         dbcc LockObjectSchema(@vc1) --- Undocu. Locks out other schema changes until commit, and increments sysobjects.schema_ver.
  3502.  
  3503.         update syscolumns set domain = @ruleid
  3504.             where id = @tab_id and colid = @colid
  3505.  
  3506.     COMMIT TRANSACTION txn_bindrule_1
  3507.  
  3508.     raiserror(15514,-1,-1)
  3509.  
  3510. end
  3511. else
  3512. begin
  3513.     /*
  3514.     **  We're binding to a user type.  In this case, the @objname
  3515.     **  is really the name of the user datatype.
  3516.     **  When we bind to a user type, any existing columns get changed
  3517.     **  to the new binding unless their current binding is not equal
  3518.     **  to the current binding for the usertype or if they set the
  3519.     **  @futureonly parameter to @futurevalue.
  3520.     */
  3521.     declare @oldrule int            /* current rule for type */
  3522.  
  3523.     /*
  3524.     **  Get the current rule for the datatype.
  3525.     */
  3526.     select @oldrule = domain, @xtype = xtype, @xusertype = xusertype
  3527.         from systypes where name = @UnqualObj and xusertype > 256
  3528.         AND (is_member('db_owner') = 1 OR is_member('db_ddladmin') = 1 OR is_member(user_name(uid))=1)
  3529.  
  3530.     if @oldrule is null
  3531.         begin
  3532.             raiserror(15105,-1,-1)
  3533.             return (1)
  3534.         end
  3535.  
  3536.     /*
  3537.     **  If the column type is image, text, or timestamp, disallow the bind.
  3538.     **  Rules can't be bound to image or text columns.
  3539.     */
  3540.     if type_name(@xtype) in ('text', 'ntext', 'image', 'timestamp')
  3541.         begin
  3542.             raiserror(15107,-1,-1)
  3543.             return (1)
  3544.         end
  3545.  
  3546.     update systypes set domain = @ruleid
  3547.             from systypes
  3548.         where xusertype = @xusertype
  3549.  
  3550.  
  3551.     raiserror(15515,-1,-1)
  3552.  
  3553.     /*
  3554.     **  Now see if there are any columns with the usertype that
  3555.     **  need the new binding.
  3556.     */
  3557.     if isnull(@futureonly, ' ') <> @futurevalue
  3558.     begin
  3559.         declare ms_crs_bindrule_1 cursor local static for
  3560.           select
  3561.             distinct
  3562.                  c.id
  3563.                 ,c.colid
  3564.             from     syscolumns c JOIN sysobjects o ON c.id = o.id AND o.xtype = N'U '
  3565.             where     c.xusertype    = @xusertype
  3566.             and    (c.domain    = @oldrule    OR
  3567.                  c.domain    = 0
  3568.                 )
  3569.             order by c.id
  3570.                   for read only
  3571.  
  3572.         open ms_crs_bindrule_1
  3573.  
  3574.         BEGIN TRANSACTION txn_bindrule_2
  3575.  
  3576.         fetch next from ms_crs_bindrule_1 into
  3577.             @tab_id
  3578.             ,@colid
  3579.  
  3580.         WHILE @@fetch_status = 0
  3581.         begin
  3582.  
  3583.             select @vc1 = quotename(user_name(OBJECTPROPERTY(@tab_id,'OwnerId'))) + '.'
  3584.                         + quotename(object_name(@tab_id))
  3585.  
  3586.             dbcc LockObjectSchema(@vc1) --- Undocu. Locks out other schema changes until commit, and increments sysobjects.schema_ver.
  3587.  
  3588.             select @cur_tab_id = @tab_id
  3589.  
  3590.             while @cur_tab_id = @tab_id and @@fetch_status = 0
  3591.             begin
  3592.                 /*
  3593.                 **  Update syscolumns with new binding.
  3594.                 */
  3595.                 update syscolumns
  3596.                     set domain = @ruleid
  3597.                     where id = @tab_id and colid = @colid
  3598.  
  3599.                 fetch next from ms_crs_bindrule_1 into
  3600.                      @tab_id
  3601.                     ,@colid
  3602.             end
  3603.  
  3604.         end --loop 3
  3605.  
  3606.         deallocate ms_crs_bindrule_1
  3607.  
  3608.         COMMIT TRANSACTION txn_bindrule_2
  3609.  
  3610.         raiserror(15516,-1,-1)
  3611.     end
  3612. end
  3613. return (0) -- sp_bindrule
  3614. go
  3615.  
  3616. raiserror(15339,-1,-1,'sp_checknames')
  3617. go
  3618. create procedure sp_checknames --- 1996/04/08 00:00
  3619. @mode varchar(20) = NULL        /* mode of operation; e.g. 'silent' */
  3620. as
  3621.  
  3622. declare @msilent    int        /* set to 1 if 'silent' mode is on */
  3623. declare @ret_val    int        /* set to 1 if we find funny char */
  3624. declare @codepoint    tinyint        /* set to 1 if we find funny char */
  3625. declare @dbname        sysname    /* holds database name */
  3626. declare @msg        varchar(90)    /* used for messages to
  3627.  */
  3628. declare @pat        varchar(132)    /* holds the pattern to search for */
  3629.  
  3630. set nocount on
  3631.  
  3632. if (@mode like '%help%')
  3633. begin
  3634.     raiserror(15525,-1,-1)
  3635.     raiserror(15526,-1,-1)
  3636.     raiserror(15527,-1,-1)
  3637.     print ' '
  3638.     raiserror(15528,-1,-1)
  3639.     raiserror('        sysdatabases.name',0,1)
  3640.     raiserror('        sysdevices.name' ,0,1)
  3641.     raiserror('        syslogins.name' ,0,1)
  3642.     raiserror('        syslogins.dbname',0,1)
  3643.     raiserror('        sysremotelogins.remoteusername',0,1)
  3644.     raiserror('        sysservers.srvname',0,1)
  3645.     raiserror('        sysservers.srvnetname',0,1)
  3646.     print ' '
  3647.     raiserror(15536,-1,-1)
  3648.     raiserror('        syscolumns.name',0,1)
  3649.     raiserror('        sysindexes.name',0,1)
  3650.     raiserror('        sysobjects.name',0,1)
  3651.     raiserror('        syssegments.name',0,1)
  3652.     raiserror('        systypes.name',0,1)
  3653.     raiserror('        sysusers.name',0,1)
  3654.     print ' '
  3655.     return (0)
  3656. end
  3657.  
  3658. /*
  3659. **  First, initialize return value, and set up mode variables:
  3660. */
  3661. select @ret_val = 0
  3662.  
  3663. if (@mode like '%silent%')
  3664.     select @msilent = 1
  3665. else
  3666.     select @msilent = 0
  3667.  
  3668.  
  3669. /*
  3670. **  Now, initialize the pattern string we will search for:
  3671. */
  3672. select @pat = '%[', @codepoint = 127
  3673. while (@codepoint < 255)
  3674. begin
  3675.     select @codepoint = @codepoint + 1
  3676.     select @pat = @pat + char(@codepoint)
  3677. end
  3678. select @pat = @pat + ']%'
  3679.  
  3680.  
  3681. /*
  3682. **  Get the database name we are in:
  3683. */
  3684. select @dbname = db_name()
  3685.  
  3686. if (@msilent = 0)
  3687. begin
  3688.     print ' '
  3689.     raiserror(15543,-1,-1,@dbname)
  3690.     print ' '
  3691. end
  3692.  
  3693.  
  3694. /*
  3695. **  Look through these only if in the master database:
  3696. */
  3697. if (@dbname = 'master')
  3698. begin
  3699.     if exists (select name from master.dbo.sysdatabases
  3700.             where convert(varchar(132), name) like @pat)
  3701.     begin
  3702.     if (@msilent = 1)
  3703.         return (1)
  3704.  
  3705.     select @ret_val = 1
  3706.     print ' '
  3707.     print '==============================================================='
  3708.     raiserror(15544,-1,-1,'sysdatabases.name')
  3709.     print ' '
  3710.     raiserror(15545,-1,-1)
  3711.     raiserror(15546,-1,-1,'sp_renamedb')
  3712.     print ' '
  3713.     select dbid,name from master.dbo.sysdatabases
  3714.             where convert(varchar(132), name) like @pat
  3715.     end
  3716.  
  3717.     if exists (select name from master.dbo.sysdevices where convert(varchar(132), name) like @pat)
  3718.     begin
  3719.     if (@msilent = 1)
  3720.         return (1)
  3721.  
  3722.     select @ret_val = 1
  3723.     print ' '
  3724.     print '==============================================================='
  3725.     raiserror(15544,-1,-1,'sysdevices.name')
  3726.     print ' '
  3727.     raiserror(15564,-1,-1)
  3728.     raiserror(15546,-1,-1,'UPDATE')
  3729.         print ' '
  3730.     select name from master.dbo.sysdevices where convert(varchar(132), name) like @pat
  3731.     end
  3732.  
  3733.     if exists (select loginname from master.dbo.syslogins where convert(varchar(132), loginname) like @pat)
  3734.     begin
  3735.     if (@msilent = 1)
  3736.         return (1)
  3737.  
  3738.     select @ret_val = 1
  3739.     print ' '
  3740.     print '==============================================================='
  3741.     raiserror(15544,-1,-1,'syslogins.name')
  3742.         print ' '
  3743.     raiserror(15565,-1,-1)
  3744.     raiserror(15546,-1,-1, 'sp_droplogin'' and ''sp_addlogin')
  3745.         print ' '
  3746.     select sid, loginname from master.dbo.syslogins
  3747.             where convert(varchar(132), loginname) like @pat
  3748.     end
  3749.  
  3750.     if exists (select dbname from master.dbo.syslogins
  3751.             where convert(varchar(132), dbname) like @pat)
  3752.     begin
  3753.     if (@msilent = 1)
  3754.         return (1)
  3755.  
  3756.     select @ret_val = 1
  3757.     print ' '
  3758.     print '==============================================================='
  3759.     raiserror(15544,-1,-1,'syslogins.dbname')
  3760.     print ' '
  3761.     raiserror(15547,-1,-1)
  3762.     raiserror(15548,-1,-1)
  3763.     raiserror(15549,-1,-1)
  3764.         print ' '
  3765.     select sid,loginname,dbname from master.dbo.syslogins
  3766.             where convert(varchar(132), dbname) like @pat
  3767.     end
  3768.  
  3769.     if exists (select remoteusername from master.dbo.sysremotelogins
  3770.             where convert(varchar(132), remoteusername) like @pat)
  3771.     begin
  3772.     if (@msilent = 1)
  3773.         return (1)
  3774.  
  3775.     select @ret_val = 1
  3776.     print ' '
  3777.     print '==============================================================='
  3778.     raiserror(15544,-1,-1,'sysremotelogins.remoteusername')
  3779.         print ' '
  3780.     raiserror(15566,-1,-1)
  3781.     raiserror(15546,-1,-1,'sp_dropremotelogin'' and ''sp_addremotelogin')
  3782.         print ' '
  3783.     select remoteserverid,remoteusername from master.dbo.sysremotelogins
  3784.             where convert(varchar(132), remoteusername) like @pat
  3785.     end
  3786.  
  3787.     if exists (select srvname from master.dbo.sysservers
  3788.             where convert(varchar(132), srvname) like @pat)
  3789.     begin
  3790.     if (@msilent = 1)
  3791.         return (1)
  3792.  
  3793.     select @ret_val = 1
  3794.     print ' '
  3795.     print '==============================================================='
  3796.     raiserror(15544,-1,-1,'sysservers.srvname')
  3797.         print ' '
  3798.     raiserror(15567,-1,-1)
  3799.     raiserror(15546,-1,-1,'sp_dropserver'' and ''sp_addserver')
  3800.         print ' '
  3801.     select srvid,srvname from master.dbo.sysservers
  3802.             where convert(varchar(132), srvname) like @pat
  3803.     end
  3804.  
  3805.     if exists (select srvnetname from master.dbo.sysservers
  3806.             where convert(varchar(132), srvnetname) like @pat)
  3807.     begin
  3808.     if (@msilent = 1)
  3809.         return (1)
  3810.  
  3811.     select @ret_val = 1
  3812.     print ' '
  3813.     print '==============================================================='
  3814.     raiserror(15544,-1,-1,'sysservers.srvnetname')
  3815.         print ' '
  3816.     raiserror(15550,-1,-1)
  3817.     raiserror(15551,-1,-1)
  3818.     raiserror(15552,-1,-1)
  3819.         print ' '
  3820.     select srvid,srvname,srvnetname from master.dbo.sysservers
  3821.             where convert(varchar(132), srvnetname) like @pat
  3822.     end
  3823.  
  3824. end
  3825.  
  3826.  
  3827. /*
  3828. **  For *ALL* databases, we want to look through these:
  3829. */
  3830. if exists (select name from dbo.syscolumns
  3831.         where convert(varchar(132), name) like @pat)
  3832. begin
  3833.     if (@msilent = 1)
  3834.     return (1)
  3835.  
  3836.     select @ret_val = 1
  3837.     print ' '
  3838.     print '==============================================================='
  3839.     raiserror(15544,-1,-1,'syscolumns.name')
  3840.     print ' '
  3841.     raiserror(15568,-1,-1)
  3842.     raiserror(15546,-1,-1,'sp_rename')
  3843.     print ' '
  3844.     select objname=o.name,colname=c.name from dbo.syscolumns c, dbo.sysobjects o
  3845.         where convert(varchar(132), c.name) like @pat and o.id = c.id
  3846. end
  3847.  
  3848. if exists (select name from dbo.sysindexes
  3849.         where convert(varchar(132), name) like @pat
  3850.               and indid > 0)
  3851. begin
  3852.     if (@msilent = 1)
  3853.     return (1)
  3854.  
  3855.     select @ret_val = 1
  3856.     print ' '
  3857.     print '==============================================================='
  3858.     raiserror(15544,-1,-1,'sysindexes.name')
  3859.     print ' '
  3860.     raiserror(15569,-1,-1)
  3861.     raiserror(15546,-1,-1,'UPDATE')
  3862.     print ' '
  3863.     select id,indid,name from dbo.sysindexes
  3864.         where convert(varchar(132), name) like @pat
  3865.         and indid > 0
  3866. end
  3867.  
  3868. if exists (select name from dbo.sysobjects
  3869.         where convert(varchar(132), name) like @pat)
  3870. begin
  3871.     if (@msilent = 1)
  3872.     return (1)
  3873.  
  3874.     select @ret_val = 1
  3875.     print ' '
  3876.     print '==============================================================='
  3877.     raiserror(15544,-1,-1,'sysobjects.name')
  3878.     print ' '
  3879.     raiserror(15570,-1,-1)
  3880.     raiserror(15546,-1,-1,'sp_rename')
  3881.     print ' '
  3882.     select owner = u.name,o.name from dbo.sysobjects o,dbo.sysusers u
  3883.         where convert(varchar(132), o.name) like @pat and o.uid=u.uid
  3884. end
  3885.  
  3886. if exists (select name from dbo.syssegments
  3887.         where convert(varchar(132), name) like @pat)
  3888. begin
  3889.     if (@msilent = 1)
  3890.     return (1)
  3891.  
  3892.     select @ret_val = 1
  3893.     print ' '
  3894.     print '==============================================================='
  3895.     raiserror(15544,-1,-1,'syssegments.name')
  3896.     print ' '
  3897.     raiserror(15571,-1,-1)
  3898.     raiserror(15546,-1,-1,'UPDATE')
  3899.     print ' '
  3900.     select segment,name from dbo.syssegments
  3901.         where convert(varchar(132), name) like @pat
  3902. end
  3903.  
  3904. if exists (select name from dbo.systypes
  3905.         where convert(varchar(132), name) like @pat)
  3906. begin
  3907.     if (@msilent = 1)
  3908.     return (1)
  3909.  
  3910.     select @ret_val = 1
  3911.     print ' '
  3912.     print '==============================================================='
  3913.     raiserror(15544,-1,-1,'systypes.name')
  3914.     print ' '
  3915.     raiserror(15572,-1,-1)
  3916.     raiserror(15546,-1,-1,'sp_rename')
  3917.     print ' '
  3918.     select name from dbo.systypes
  3919.         where convert(varchar(132), name) like @pat
  3920. end
  3921.  
  3922. if exists (select name from dbo.sysusers where convert(varchar(132), name) like @pat)
  3923. begin
  3924.     if (@msilent = 1)
  3925.     return (1)
  3926.  
  3927.     select @ret_val = 1
  3928.     print ' '
  3929.     print '==============================================================='
  3930.     raiserror(15544,-1,-1,'sysusers.name')
  3931.     print ' '
  3932.     raiserror(15573,-1,-1)
  3933.     raiserror(15546,-1,-1,'UPDATE')
  3934.     print ' '
  3935.     select sid,uid,name from dbo.sysusers
  3936.         where convert(varchar(132), name) like @pat
  3937. end
  3938.  
  3939. if (@ret_val = 0  and  @msilent = 0)
  3940. begin
  3941.  
  3942.     raiserror(15553,-1,-1, @dbname)
  3943.     raiserror(15554,-1,-1)
  3944. end
  3945.  
  3946. return (@ret_val) -- sp_checknames
  3947. go
  3948.  
  3949. checkpoint
  3950. go
  3951.  
  3952. raiserror(15339,-1,-1,'sp_configure')
  3953. go
  3954. CREATE PROCEDURE sp_configure  --- 1996/08/14 09:43
  3955.  
  3956.     @configname   varchar(35) = NULL   -- option name to configure
  3957.    ,@configvalue  int         = NULL   -- new configuration value
  3958. as
  3959.  
  3960. set nocount on
  3961.  
  3962. declare
  3963.     @confignum                int   --Num of the opt to be configured
  3964.    ,@configcount              int   --Num of options like @configname
  3965.    ,@show_advance             int   --Y/N Read&Write actions on "advanced" opts
  3966.  
  3967. declare @fullconfigname        varchar (35)
  3968. declare @prevvalue            int
  3969. /*
  3970. **  Determine @maxnumber based on advance option in syscurconfigs.
  3971. */
  3972. if (select value from master.dbo.syscurconfigs where config = 518) = 1
  3973.    select @show_advance = 1   -- Display advanced options
  3974. else
  3975.    select @show_advance = 0   -- Don't display advanced options
  3976.  
  3977. /*
  3978. **  Make certain that max user info. reflects any addpak upgrades.
  3979. */
  3980. if (select high from master.dbo.spt_values where number=103 and type='C')
  3981.    <> @@max_connections
  3982.  
  3983.    update master.dbo.spt_values
  3984.       set high = @@max_connections
  3985.       where number = 103
  3986.          and type='C'
  3987.  
  3988. /*
  3989. **  If no option name is given, the procedure will just print out all the
  3990. **  options and their values.
  3991. */
  3992. if @configname is NULL
  3993.    begin
  3994.       select name, minimum = low, maximum = high,
  3995.          config_value = c.value,
  3996.          run_value = master.dbo.syscurconfigs.value
  3997.       from master.dbo.spt_values, master.dbo.sysconfigures c, master.dbo.syscurconfigs
  3998.       where type = 'C'
  3999.          and number = c.config
  4000.          and number = master.dbo.syscurconfigs.config
  4001.  
  4002.          and
  4003.              ((c.status & 2 <> 0 and @show_advance = 1)
  4004.                   OR
  4005.               (c.status & 2  = 0)
  4006.              )
  4007.       order by lower(name)
  4008.  
  4009.       return (0)
  4010.    end
  4011.  
  4012. /*
  4013. **  Use @configname and try to find the right option.
  4014. **  If there isn't just one, print appropriate diagnostics and return.
  4015. */
  4016. select @configcount = count(*), @fullconfigname = min (v.name), @prevvalue = min (c.value)
  4017.    from master.dbo.spt_values v ,master.dbo.sysconfigures c
  4018.    where v.name like '%' + @configname + '%' and v.type = 'C'
  4019.       and v.number = c.config
  4020.       and
  4021.             ((c.status & 2 <> 0 and @show_advance = 1)
  4022.                   OR
  4023.              (c.status & 2  = 0)
  4024.             )
  4025.  
  4026. /*
  4027. **  If no option, show the user what the options are.
  4028. */
  4029. if @configcount = 0
  4030.    begin
  4031.       raiserror (15123,-1,-1,@configname)
  4032.  
  4033.       print ' '
  4034.       raiserror (15456,-1,-1)
  4035.  
  4036.       /*
  4037.       ** Show the user what the options are.
  4038.       */
  4039.       select name, minimum = low, maximum = high,
  4040.          config_value = c.value,
  4041.          run_value = master.dbo.syscurconfigs.value
  4042.       from master.dbo.spt_values, master.dbo.sysconfigures c, master.dbo.syscurconfigs
  4043.       where type = 'C'
  4044.          and number = c.config
  4045.          and number = master.dbo.syscurconfigs.config
  4046.  
  4047.          and
  4048.              ((c.status & 2 <> 0 and @show_advance = 1)
  4049.                    OR
  4050.               (c.status & 2  = 0)
  4051.              )
  4052.  
  4053.       return (1)
  4054.    end
  4055.  
  4056. /*
  4057. **  If more than one option like @configname, show the duplicates and return.
  4058. */
  4059. if @configcount > 1
  4060.    begin
  4061.       raiserror (15124,-1,-1,@configname)
  4062.       print ' '
  4063.  
  4064.       select duplicate_options = name
  4065.       from master.dbo.spt_values,master.dbo.sysconfigures c
  4066.       where name like '%' + @configname + '%'
  4067.          and type = 'C'
  4068.          and number = c.config
  4069.          and
  4070.              ((c.status & 2 <> 0 and @show_advance = 1)
  4071.                    OR
  4072.               (c.status & 2  = 0)
  4073.              )
  4074.  
  4075.       return (1)
  4076.    end
  4077. else
  4078.    /* There must be exactly one, so get the full name. */
  4079.    select @configname = name --,@value_in_sysconfigures = c.value
  4080.       from master.dbo.spt_values,master.dbo.sysconfigures c
  4081.       where name like '%' + @configname + '%' and type = 'C'
  4082.          and number = c.config
  4083.          and
  4084.              ((c.status & 2 <> 0 and @show_advance = 1)
  4085.                    OR
  4086.               (c.status & 2  = 0)
  4087.              )
  4088.  
  4089. /*
  4090. ** If @configvalue is NULL, just show the current state of the option.
  4091. */
  4092. if @configvalue is null
  4093. begin
  4094.  
  4095.    select       v.name
  4096.                ,v.low   as 'minimum'
  4097.                ,v.high  as 'maximum'
  4098.                ,c.value as 'config_value'
  4099.                ,u.value as 'run_value'
  4100.          from
  4101.                 master.dbo.spt_values     v  left outer join
  4102.                 master.dbo.sysconfigures  c  on v.number = c.config
  4103.                                              left outer join
  4104.                 master.dbo.syscurconfigs  u  on v.number = u.config
  4105.          where
  4106.                 v.type = 'C  '
  4107.          and    v.name like '%' + @configname + '%'
  4108.          and
  4109.                ((c.status & 2 <> 0 and @show_advance = 1)
  4110.                      OR
  4111.                 (c.status & 2  = 0)
  4112.                )
  4113.  
  4114.    return (0)
  4115. end
  4116.  
  4117. /*
  4118. **  Check.Permissions
  4119. */
  4120. if (not is_srvrolemember('serveradmin') = 1)
  4121.    begin
  4122.       raiserror(15247,-1,-1)
  4123.       return (1)
  4124.    end
  4125.  
  4126. /*
  4127. **  Now get the configuration number.
  4128. */
  4129. select @confignum = number
  4130.    from master.dbo.spt_values,master.dbo.sysconfigures c
  4131.    where type = 'C'
  4132.       and (@configvalue between low and high or @configvalue = 0)
  4133.       and name like '%' + @configname + '%'
  4134.       and number = c.config
  4135.       and
  4136.             ((c.status & 2 <> 0 and @show_advance = 1)
  4137.                   OR
  4138.              (c.status & 2  = 0)
  4139.             )
  4140.  
  4141. /*
  4142. **  If this is the number of default language, we want to make sure
  4143. **  that the new value is a valid language id in Syslanguages.
  4144. */
  4145. if @confignum = 124
  4146.    begin
  4147.    if not exists (select * from master.dbo.syslanguages
  4148.          where langid = @configvalue)
  4149.       begin
  4150.          /* 0 is default language, us_english */
  4151.          if @configvalue <> 0
  4152.             begin
  4153.                raiserror(15127,-1,-1)
  4154.                return (1)
  4155.             end
  4156.       end
  4157.    end
  4158.  
  4159. /*
  4160. **  If this is the number of kernel language, we want to make sure
  4161. **  that the new value is a valid language id in Syslanguages.
  4162. */
  4163. if @confignum = 132
  4164.    begin
  4165.    if not exists (select * from master.dbo.syslanguages
  4166.          where langid = @configvalue)
  4167.       begin
  4168.          /* 0 is default language, us_english */
  4169.          if @configvalue <> 0
  4170.             begin
  4171.                raiserror(15028,-1,-1)
  4172.                return (1)
  4173.             end
  4174.       end
  4175.    end
  4176.  
  4177. /*
  4178. **  "user options" should not try to set incompatible options/values.
  4179. */
  4180. if @confignum = 1534  --"user options"
  4181.    begin
  4182.  
  4183.    if (@configvalue & (1024+2048) = (1024+2048)) --ansi_null_default_on/off
  4184.       begin
  4185.       raiserror(15303,-1,-1,@configvalue)
  4186.       return (1)
  4187.       end
  4188.    end
  4189.  
  4190. /*
  4191. **  Although the @configname is good, @configvalue wasn't in range.
  4192. */
  4193. if @confignum is NULL
  4194.    begin
  4195.    raiserror(15129,-1,-1,@configvalue,@configname)
  4196.    return (1)
  4197.    end
  4198.  
  4199. --Msg 15002, but in 6.5 allow this inside a txn (not check @@trancount) #12828.
  4200.  
  4201. /*
  4202. **  Now update sysconfigures.
  4203. */
  4204. update master.dbo.sysconfigures set value = @configvalue
  4205.    where config = @confignum
  4206.  
  4207. /*
  4208. ** Flush the procedure cache - this is to account for options which become
  4209. ** effective immediately (ie. dont need a server restart).
  4210. */
  4211. dbcc freeproccache
  4212.  
  4213. raiserror(15457,-1,-1, @fullconfigname, @prevvalue, @configvalue) with log
  4214.  
  4215. return (0) -- sp_configure
  4216. go
  4217.  
  4218.  
  4219. checkpoint
  4220. go
  4221.  
  4222.  
  4223.  
  4224. raiserror(15339,-1,-1,'sp_dbremove')
  4225. go
  4226. create procedure sp_dbremove --- 1996/04/08 00:00
  4227. @dbname sysname = null,
  4228. @dropdev varchar(10) = null
  4229. as
  4230.     declare @dbid int
  4231.     declare @devname sysname
  4232.     declare @physname varchar(255)
  4233.  
  4234.     if @dbname is null
  4235.         begin
  4236.             raiserror(15131,-1,-1)
  4237.             return(1)
  4238.         end
  4239.  
  4240.     if lower(@dropdev) <> 'dropdev' and @dropdev is not null
  4241.         begin
  4242.             raiserror(15131,-1,-1)
  4243.             return(1)
  4244.         end
  4245.  
  4246.     /* Check to see if database exists. */
  4247.     select @dbid = null
  4248.     select @dbid = dbid from master.dbo.sysdatabases where name=@dbname
  4249.     if @dbid is null
  4250.         begin
  4251.             raiserror(15010,-1,-1,@dbname)
  4252.             return(1)
  4253.         end
  4254.  
  4255.     /* Make sure no one is in the db. */
  4256.     if (select count(*) from master.dbo.sysprocesses where dbid = @dbid) > 0
  4257.         begin
  4258.             raiserror(15069,-1,-1)
  4259.             return (1)
  4260.         end
  4261.  
  4262.     update master.dbo.sysdatabases set status = 256 where dbid=@dbid
  4263.     dbcc dbrepair(@dbname,dropdb,noinit)
  4264.     raiserror(15458,-1,-1)
  4265.  
  4266.     return(0)
  4267. -- sp_dbremove
  4268. go
  4269.  
  4270.  
  4271.  
  4272.  
  4273. raiserror(15339,-1,-1,'sp_create_removable')
  4274. go
  4275. create procedure sp_create_removable
  4276.  
  4277. @dbname        sysname = null,    /* name of db */
  4278. @syslogical    sysname = null,    /* logical name of system device */
  4279. @sysphysical    nvarchar (260) = null,    /* physical name of system device */
  4280. @syssize    int = null,        /* size of sys device in Meg. */
  4281. @loglogical    sysname = null,    /* logical name of log device */
  4282. @logphysical    nvarchar (260) = null,    /* physical name of log device */
  4283. @logsize    int = null,        /* size of log device in Meg. */
  4284. @datalogical1    sysname = null,    /* logical name of data device */
  4285. @dataphysical1    nvarchar (260) = null,    /* physical name of data device */
  4286. @datasize1    int = null,        /* size of data device in Meg. */
  4287. @datalogical2    sysname = null,    /* logical name of data device */
  4288. @dataphysical2    nvarchar (260) = null,    /* physical name of data device */
  4289. @datasize2    int = null,        /* size of data device in Meg. */
  4290. @datalogical3    sysname = null,    /* logical name of data device */
  4291. @dataphysical3    nvarchar (260) = null,    /* physical name of data device */
  4292. @datasize3    int = null,        /* size of data device in Meg. */
  4293. @datalogical4    sysname = null,    /* logical name of data device */
  4294. @dataphysical4    nvarchar (260) = null,    /* physical name of data device */
  4295. @datasize4    int = null,        /* size of data device in Meg. */
  4296. @datalogical5    sysname = null,    /* logical name of data device */
  4297. @dataphysical5    nvarchar (260) = null,    /* physical name of data device */
  4298. @datasize5    int = null,        /* size of data device in Meg. */
  4299. @datalogical6    sysname = null,    /* logical name of data device */
  4300. @dataphysical6    nvarchar (260) = null,    /* physical name of data device */
  4301. @datasize6    int = null,        /* size of data device in Meg. */
  4302. @datalogical7    sysname = null,    /* logical name of data device */
  4303. @dataphysical7    nvarchar (260) = null,    /* physical name of data device */
  4304. @datasize7    int = null,        /* size of data device in Meg. */
  4305. @datalogical8    sysname = null,    /* logical name of data device */
  4306. @dataphysical8    nvarchar (260) = null,    /* physical name of data device */
  4307. @datasize8    int = null,        /* size of data device in Meg. */
  4308. @datalogical9    sysname = null,    /* logical name of data device */
  4309. @dataphysical9    nvarchar (260) = null,    /* physical name of data device */
  4310. @datasize9    int = null,        /* size of data device in Meg. */
  4311. @datalogical10    sysname = null,    /* logical name of data device */
  4312. @dataphysical10    nvarchar (260) = null,    /* physical name of data device */
  4313. @datasize10    int = null,        /* size of data device in Meg. */
  4314. @datalogical11    sysname = null,    /* logical name of data device */
  4315. @dataphysical11    nvarchar (260) = null,    /* physical name of data device */
  4316. @datasize11    int = null,        /* size of data device in Meg. */
  4317. @datalogical12    sysname = null,    /* logical name of data device */
  4318. @dataphysical12    nvarchar (260) = null,    /* physical name of data device */
  4319. @datasize12    int = null,        /* size of data device in Meg. */
  4320. @datalogical13    sysname = null,    /* logical name of data device */
  4321. @dataphysical13    nvarchar (260) = null,    /* physical name of data device */
  4322. @datasize13    int = null,        /* size of data device in Meg. */
  4323. @datalogical14    sysname = null,    /* logical name of data device */
  4324. @dataphysical14    nvarchar (260) = null,    /* physical name of data device */
  4325. @datasize14    int = null,        /* size of data device in Meg. */
  4326. @datalogical15    sysname = null,    /* logical name of data device */
  4327. @dataphysical15    nvarchar (260) = null,    /* physical name of data device */
  4328. @datasize15    int = null,        /* size of data device in Meg. */
  4329. @datalogical16    sysname = null,    /* logical name of data device */
  4330. @dataphysical16 nvarchar (260) = null,    /* physical name of data device */
  4331. @datasize16    int = null        /* size of data device in Meg. */
  4332.  
  4333. as
  4334.  
  4335. declare @retcode int,
  4336.     @exec_str nvarchar (460),
  4337.     @numdevs int
  4338.  
  4339. if (not (is_srvrolemember('sysadmin') = 1)) -- Make sure that it's the SA executing this.
  4340.     begin
  4341.         raiserror(15247,-1,-1)
  4342.         return(1)
  4343.     end
  4344.  
  4345. if @dbname is null
  4346.     or @syslogical is null
  4347.     or @sysphysical is null
  4348.     or @syssize is null
  4349.     or @loglogical is null
  4350.     or @logphysical is null
  4351.     or @logsize is null
  4352.     or @datalogical1 is null
  4353.     or @dataphysical1 is null
  4354.     or @datasize1 is null
  4355.         begin
  4356.             raiserror (15261,-1,-1)
  4357.             return (1)
  4358.         end
  4359.  
  4360. if exists (select * from master.dbo.sysdatabases where name = @dbname)
  4361.     begin
  4362.         raiserror(15032,-1,-1,@dbname)
  4363.         return(1)
  4364.     end
  4365.  
  4366. /* Check to verify that valid sizes were supplied for required devices. */
  4367. if @syssize < 1 or @logsize < 1 or @datasize1 < 1
  4368.     begin
  4369.         raiserror (15262,-1,-1)
  4370.         return(1)
  4371.     end
  4372.  
  4373. /* Check to see if a valid database name was supplied. */
  4374. exec @retcode = sp_validname @dbname
  4375. if @retcode <> 0
  4376.     return(1)
  4377.  
  4378. /* valid syslogical? */
  4379. exec @retcode = sp_validname @syslogical
  4380. if @retcode <> 0
  4381.     return(1)
  4382.  
  4383. /* valid loglogical? */
  4384. exec @retcode = sp_validname @loglogical
  4385. if @retcode <> 0
  4386.     return(1)
  4387.  
  4388. /* valid datalogical1? */
  4389. exec @retcode = sp_validname @datalogical1
  4390. if @retcode <> 0
  4391.     return(1)
  4392.  
  4393.  
  4394. /* Create the database's system device segment. */
  4395. select @exec_str = 'CREATE DATABASE '
  4396.         + quotename( @dbname , '[')
  4397.         + ' ON (NAME ='
  4398.         + quotename( @syslogical , '[')
  4399.         + ',FILENAME ='
  4400.         + ''''
  4401.         + @sysphysical
  4402.         + ''''
  4403.         + ',SIZE ='
  4404.         + convert(varchar(28),@syssize)
  4405.         + ') LOG ON (NAME='
  4406.         + quotename( @loglogical , '[')
  4407.         + ',FILENAME ='
  4408.         + ''''
  4409.         + @logphysical
  4410.         + ''''
  4411.         + ',SIZE ='
  4412.         + convert(varchar(28),@logsize)
  4413.         + ')'
  4414. exec(@exec_str)
  4415.  
  4416. if @@error <> 0
  4417.     begin
  4418.         raiserror(15264,-1,-1,'system or log')
  4419.         return(1)
  4420.     end
  4421.  
  4422. -- Add a filegroup for data
  4423. select @exec_str = 'ALTER DATABASE '
  4424.         + quotename( @dbname , '[')
  4425.         + ' ADD FILEGROUP readonlyfilegroup'
  4426.  
  4427. exec(@exec_str)
  4428.  
  4429. if @@error <> 0
  4430.     begin
  4431.         raiserror(15264,-1,-1,'user filegroup')
  4432.         return(1)
  4433.     end
  4434.  
  4435. select @exec_str = 'ALTER DATABASE '
  4436.         + quotename( @dbname , '[')
  4437.         +' ADD FILE (NAME ='
  4438.         + quotename( @datalogical1 , '[')
  4439.         + ',FILENAME ='
  4440.         + ''''
  4441.         + @dataphysical1
  4442.         + ''''
  4443.         + ',SIZE ='
  4444.         + convert(varchar(28),@datasize1)
  4445.         + ') TO FILEGROUP readonlyfilegroup'
  4446.         exec(@exec_str)
  4447.  
  4448. if @@error <> 0
  4449.     begin
  4450.         raiserror(15264,-1,-1,'user data')
  4451.         exec ('drop database '+ @dbname)
  4452.         return(1)
  4453.     end
  4454.  
  4455. -- Make this the default filegroup
  4456. select @exec_str = 'ALTER DATABASE '
  4457.         + quotename( @dbname , '[')
  4458.         + ' MODIFY FILEGROUP readonlyfilegroup DEFAULT'
  4459.  
  4460. exec(@exec_str)
  4461.  
  4462. if @@error <> 0
  4463.     begin
  4464.         raiserror(15264,-1,-1,'default filegroup')
  4465.         return(1)
  4466.     end
  4467.  
  4468.  
  4469. /* Check out optional data devices. */
  4470.  
  4471. if @datalogical2 is not null
  4472. begin
  4473.     select @exec_str = 'ALTER DATABASE '
  4474.         + quotename( @dbname , '[')
  4475.         +' ADD FILE (NAME ='
  4476.         + quotename( @datalogical2 , '[')
  4477.         + ',FILENAME ='
  4478.         + ''''
  4479.         + @dataphysical2
  4480.         + ''''
  4481.         + ',SIZE ='
  4482.         + convert(varchar(28),@datasize2)
  4483.         + ') TO FILEGROUP readonlyfilegroup'
  4484.     exec(@exec_str)
  4485.     if @retcode <> 0
  4486.     begin
  4487.         raiserror(15269,-1,-1,@datalogical2)
  4488.         exec ('drop database '+ @dbname)
  4489.         return(1)
  4490.     end
  4491.     select @numdevs = 2
  4492. end
  4493. else goto no_more_devs
  4494.  
  4495. if @datalogical3 is not null
  4496. begin
  4497.     select @exec_str = 'ALTER DATABASE '
  4498.         + quotename( @dbname , '[')
  4499.         +' ADD FILE (NAME ='
  4500.         + quotename( @datalogical3 , '[')
  4501.         + ',FILENAME ='
  4502.         + ''''
  4503.         + @dataphysical3
  4504.         + ''''
  4505.         + ',SIZE ='
  4506.         + convert(varchar(28),@datasize3)
  4507.         + ') TO FILEGROUP readonlyfilegroup'
  4508.     exec(@exec_str)
  4509.     if @retcode <> 0
  4510.     begin
  4511.         raiserror(15269,-1,-1,@datalogical3)
  4512.         exec ('drop database '+ @dbname)
  4513.         return(1)
  4514.     end
  4515.     select @numdevs = 3
  4516. end
  4517. else goto no_more_devs
  4518.  
  4519. if @datalogical4 is not null
  4520. begin
  4521.     select @exec_str = 'ALTER DATABASE '
  4522.         + quotename( @dbname , '[')
  4523.         +' ADD FILE (NAME ='
  4524.         + quotename( @datalogical4 , '[')
  4525.         + ',FILENAME ='
  4526.         + ''''
  4527.         + @dataphysical4
  4528.         + ''''
  4529.         + ',SIZE ='
  4530.         + convert(varchar(28),@datasize4)
  4531.         + ') TO FILEGROUP readonlyfilegroup'
  4532.     exec(@exec_str)
  4533.     if @retcode <> 0
  4534.     begin
  4535.         raiserror(15269,-1,-1,@datalogical4)
  4536.         exec ('drop database '+ @dbname)
  4537.         return(1)
  4538.     end
  4539.     select @numdevs = 4
  4540. end
  4541. else goto no_more_devs
  4542.  
  4543. if @datalogical5 is not null
  4544. begin
  4545.     select @exec_str = 'ALTER DATABASE '
  4546.         + quotename( @dbname , '[')
  4547.         +' ADD FILE (NAME ='
  4548.         + quotename( @datalogical5 , '[')
  4549.         + ',FILENAME ='
  4550.         + ''''
  4551.         + @dataphysical5
  4552.         + ''''
  4553.         + ',SIZE ='
  4554.         + convert(varchar(28),@datasize5)
  4555.         + ') TO FILEGROUP readonlyfilegroup'
  4556.     exec(@exec_str)
  4557.     if @retcode <> 0
  4558.     begin
  4559.         raiserror(15269,-1,-1,@datalogical5)
  4560.         exec ('drop database '+ @dbname)
  4561.         return(1)
  4562.     end
  4563.     select @numdevs = 5
  4564. end
  4565. else goto no_more_devs
  4566.  
  4567. if @datalogical6 is not null
  4568. begin
  4569.     select @exec_str = 'ALTER DATABASE '
  4570.         + quotename( @dbname , '[')
  4571.         +' ADD FILE (NAME ='
  4572.         + quotename( @datalogical6 , '[')
  4573.         + ',FILENAME ='
  4574.         + ''''
  4575.         + @dataphysical6
  4576.         + ''''
  4577.         + ',SIZE ='
  4578.         + convert(varchar(28),@datasize6)
  4579.         + ') TO FILEGROUP readonlyfilegroup'
  4580.     exec(@exec_str)
  4581.     if @retcode <> 0
  4582.     begin
  4583.         raiserror(15269,-1,-1,@datalogical6)
  4584.         exec ('drop database '+ @dbname)
  4585.         return(1)
  4586.     end
  4587.     select @numdevs = 6
  4588. end
  4589. else goto no_more_devs
  4590.  
  4591. if @datalogical7 is not null
  4592. begin
  4593.     select @exec_str = 'ALTER DATABASE '
  4594.         + quotename( @dbname , '[')
  4595.         +' ADD FILE (NAME ='
  4596.         + quotename( @datalogical7 , '[')
  4597.         + ',FILENAME ='
  4598.         + ''''
  4599.         + @dataphysical7
  4600.         + ''''
  4601.         + ',SIZE ='
  4602.         + convert(varchar(28),@datasize7)
  4603.         + ') TO FILEGROUP readonlyfilegroup'
  4604.     exec(@exec_str)
  4605.     if @retcode <> 0
  4606.     begin
  4607.         raiserror(15269,-1,-1,@datalogical7)
  4608.         exec ('drop database '+ @dbname)
  4609.         return(1)
  4610.     end
  4611.     select @numdevs = 7
  4612. end
  4613. else goto no_more_devs
  4614.  
  4615. if @datalogical8 is not null
  4616. begin
  4617.     select @exec_str = 'ALTER DATABASE '
  4618.         + quotename( @dbname , '[')
  4619.         +' ADD FILE (NAME ='
  4620.         + quotename( @datalogical8 , '[')
  4621.         + ',FILENAME ='
  4622.         + ''''
  4623.         + @dataphysical8
  4624.         + ''''
  4625.         + ',SIZE ='
  4626.         + convert(varchar(28),@datasize8)
  4627.         + ') TO FILEGROUP readonlyfilegroup'
  4628.     exec(@exec_str)
  4629.     if @retcode <> 0
  4630.     begin
  4631.         raiserror(15269,-1,-1,@datalogical8)
  4632.         exec ('drop database '+ @dbname)
  4633.         return(1)
  4634.     end
  4635.     select @numdevs = 8
  4636. end
  4637. else goto no_more_devs
  4638. if @datalogical9 is not null
  4639. begin
  4640.     select @exec_str = 'ALTER DATABASE '
  4641.         + quotename( @dbname , '[')
  4642.         +' ADD FILE (NAME ='
  4643.         + quotename( @datalogical9 , '[')
  4644.         + ',FILENAME ='
  4645.         + ''''
  4646.         + @dataphysical9
  4647.         + ''''
  4648.         + ',SIZE ='
  4649.         + convert(varchar(28),@datasize9)
  4650.         + ') TO FILEGROUP readonlyfilegroup'
  4651.     exec(@exec_str)
  4652.     if @retcode <> 0
  4653.     begin
  4654.         raiserror(15269,-1,-1,@datalogical9)
  4655.         exec ('drop database '+ @dbname)
  4656.         return(1)
  4657.     end
  4658.     select @numdevs = 9
  4659. end
  4660. else goto no_more_devs
  4661.  
  4662. if @datalogical10 is not null
  4663. begin
  4664.     select @exec_str = 'ALTER DATABASE '
  4665.         + quotename( @dbname , '[')
  4666.         +' ADD FILE (NAME ='
  4667.         + quotename( @datalogical10 , '[')
  4668.         + ',FILENAME ='
  4669.         + ''''
  4670.         + @dataphysical10
  4671.         + ''''
  4672.         + ',SIZE ='
  4673.         + convert(varchar(28),@datasize10)
  4674.         + ') TO FILEGROUP readonlyfilegroup'
  4675.     exec(@exec_str)
  4676.     if @retcode <> 0
  4677.     begin
  4678.         raiserror(15269,-1,-1,@datalogical10)
  4679.         exec ('drop database '+ @dbname)
  4680.         return(1)
  4681.     end
  4682.     select @numdevs = 10
  4683. end
  4684. else goto no_more_devs
  4685.  
  4686. if @datalogical11 is not null
  4687. begin
  4688.     select @exec_str = 'ALTER DATABASE '
  4689.         + quotename( @dbname , '[')
  4690.         +' ADD FILE (NAME ='
  4691.         + quotename( @datalogical11 , '[')
  4692.         + ',FILENAME ='
  4693.         + ''''
  4694.         + @dataphysical11
  4695.         + ''''
  4696.         + ',SIZE ='
  4697.         + convert(varchar(28),@datasize11)
  4698.         + ') TO FILEGROUP readonlyfilegroup'
  4699.     exec(@exec_str)
  4700.     if @retcode <> 0
  4701.     begin
  4702.         raiserror(15269,-1,-1,@datalogical11)
  4703.         exec ('drop database '+ @dbname)
  4704.         return(1)
  4705.     end
  4706.     select @numdevs = 11
  4707. end
  4708. else goto no_more_devs
  4709.  
  4710. if @datalogical12 is not null
  4711. begin
  4712.     select @exec_str = 'ALTER DATABASE '
  4713.         + quotename( @dbname , '[')
  4714.         +' ADD FILE (NAME ='
  4715.         + quotename( @datalogical12 , '[')
  4716.         + ',FILENAME ='
  4717.         + ''''
  4718.         + @dataphysical12
  4719.         + ''''
  4720.         + ',SIZE ='
  4721.         + convert(varchar(28),@datasize12)
  4722.         + ') TO FILEGROUP readonlyfilegroup'
  4723.     exec(@exec_str)
  4724.     if @retcode <> 0
  4725.     begin
  4726.         raiserror(15269,-1,-1,@datalogical12)
  4727.         exec ('drop database '+ @dbname)
  4728.         return(1)
  4729.     end
  4730.     select @numdevs = 12
  4731. end
  4732. else goto no_more_devs
  4733.  
  4734. if @datalogical13 is not null
  4735. begin
  4736.     select @exec_str = 'ALTER DATABASE '
  4737.         + quotename( @dbname , '[')
  4738.         +' ADD FILE (NAME ='
  4739.         + quotename( @datalogical13 , '[')
  4740.         + ',FILENAME ='
  4741.         + ''''
  4742.         + @dataphysical13
  4743.         + ''''
  4744.         + ',SIZE ='
  4745.         + convert(varchar(28),@datasize13)
  4746.         + ') TO FILEGROUP readonlyfilegroup'
  4747.     exec(@exec_str)
  4748.     if @retcode <> 0
  4749.     begin
  4750.         raiserror(15269,-1,-1,@datalogical13)
  4751.         exec ('drop database '+ @dbname)
  4752.         return(1)
  4753.     end
  4754.     select @numdevs = 13
  4755. end
  4756. else goto no_more_devs
  4757.  
  4758. if @datalogical14 is not null
  4759. begin
  4760.     select @exec_str = 'ALTER DATABASE '
  4761.         + quotename( @dbname , '[')
  4762.         +' ADD FILE (NAME ='
  4763.         + quotename( @datalogical14 , '[')
  4764.         + ',FILENAME ='
  4765.         + ''''
  4766.         + @dataphysical14
  4767.         + ''''
  4768.         + ',SIZE ='
  4769.         + convert(varchar(28),@datasize14)
  4770.         + ') TO FILEGROUP readonlyfilegroup'
  4771.     exec(@exec_str)
  4772.     if @retcode <> 0
  4773.     begin
  4774.         raiserror(15269,-1,-1,@datalogical14)
  4775.         exec ('drop database '+ @dbname)
  4776.         return(1)
  4777.     end
  4778.     select @numdevs = 14
  4779. end
  4780. else goto no_more_devs
  4781.  
  4782. if @datalogical15 is not null
  4783. begin
  4784.     select @exec_str = 'ALTER DATABASE '
  4785.         + quotename( @dbname , '[')
  4786.         +' ADD FILE (NAME ='
  4787.         + quotename( @datalogical15 , '[')
  4788.         + ',FILENAME ='
  4789.         + ''''
  4790.         + @dataphysical15
  4791.         + ''''
  4792.         + ',SIZE ='
  4793.         + convert(varchar(28),@datasize15)
  4794.         + ') TO FILEGROUP readonlyfilegroup'
  4795.     exec(@exec_str)
  4796.     if @retcode <> 0
  4797.     begin
  4798.         raiserror(15269,-1,-1,@datalogical15)
  4799.         exec ('drop database '+ @dbname)
  4800.         return(1)
  4801.     end
  4802.     select @numdevs = 15
  4803. end
  4804. else goto no_more_devs
  4805.  
  4806. if @datalogical16 is not null
  4807. begin
  4808.     select @exec_str = 'ALTER DATABASE '
  4809.         + quotename( @dbname , '[')
  4810.         +' ADD FILE (NAME ='
  4811.         + quotename( @datalogical16 , '[')
  4812.         + ',FILENAME ='
  4813.         + ''''
  4814.         + @dataphysical16
  4815.         + ''''
  4816.         + ',SIZE ='
  4817.         + convert(varchar(28),@datasize16)
  4818.         + ') TO FILEGROUP readonlyfilegroup'
  4819.     exec(@exec_str)
  4820.     if @retcode <> 0
  4821.     begin
  4822.         raiserror(15269,-1,-1,@datalogical16)
  4823.         exec ('drop database '+ @dbname)
  4824.         return(1)
  4825.     end
  4826.     select @numdevs = 16
  4827. end
  4828.  
  4829. no_more_devs:
  4830.  
  4831.  
  4832. return(0) -- sp_create_removable
  4833. go
  4834.  
  4835.  
  4836.  
  4837. raiserror(15339,-1,-1,'sp_depends')
  4838. go
  4839. create procedure sp_depends  --- 1996/08/09 16:51
  4840. @objname nvarchar(776)        /* the object we want to check */
  4841. as
  4842.  
  4843. declare @objid int            /* the id of the object we want */
  4844. declare @found_some bit            /* flag for dependencies found */
  4845. declare @dbname sysname
  4846.  
  4847. /*
  4848. **  Make sure the @objname is local to the current database.
  4849. */
  4850.  
  4851. select @dbname = parsename(@objname,3)
  4852.  
  4853. if @dbname is not null and @dbname <> db_name()
  4854.     begin
  4855.         raiserror(15250,-1,-1)
  4856.         return (1)
  4857.     end
  4858.  
  4859. /*
  4860. **  See if @objname exists.
  4861. */
  4862. select @objid = object_id(@objname)
  4863. if @objid is null
  4864.     begin
  4865.         select @dbname = db_name()
  4866.         raiserror(15009,-1,-1,@objname,@dbname)
  4867.         return (1)
  4868.     end
  4869.  
  4870. /*
  4871. **  Initialize @found_some to indicate that we haven't seen any dependencies.
  4872. */
  4873. select @found_some = 0
  4874.  
  4875. set nocount on
  4876.  
  4877. /*
  4878. **  Print out the particulars about the local dependencies.
  4879. */
  4880. if exists (select *
  4881.         from sysdepends
  4882.             where id = @objid)
  4883. begin
  4884.     raiserror(15459,-1,-1)
  4885.     select         'name' = (s6.name+ '.' + o1.name),
  4886.              type = substring(v2.name, 5, 16),
  4887.              updated = substring(u4.name, 1, 7),
  4888.              selected = substring(w5.name, 1, 8),
  4889.              'column' = col_name(d3.depid, d3.depnumber)
  4890.         from     sysobjects        o1
  4891.             ,master.dbo.spt_values    v2
  4892.             ,sysdepends        d3
  4893.             ,master.dbo.spt_values    u4
  4894.             ,master.dbo.spt_values    w5 --11667
  4895.             ,sysusers        s6
  4896.         where     o1.id = d3.depid
  4897.         and     o1.xtype = substring(v2.name,1,2) collate database_default and v2.type = 'O9T'
  4898.         and     u4.type = 'B' and u4.number = d3.resultobj
  4899.         and     w5.type = 'B' and w5.number = d3.readobj|d3.selall
  4900.         and     d3.id = @objid
  4901.         and     o1.uid = s6.uid
  4902.         and deptype < 2
  4903.  
  4904.     select @found_some = 1
  4905. end
  4906.  
  4907. /*
  4908. **  Now check for things that depend on the object.
  4909. */
  4910. if exists (select *
  4911.         from sysdepends
  4912.             where depid = @objid)
  4913. begin
  4914.         raiserror(15460,-1,-1)
  4915.     select distinct 'name' = (s.name + '.' + o.name),
  4916.         type = substring(v.name, 5, 16)
  4917.             from sysobjects o, master.dbo.spt_values v, sysdepends d,
  4918.                 sysusers s
  4919.             where o.id = d.id
  4920.                 and o.xtype = substring(v.name,1,2) collate database_default and v.type = 'O9T'
  4921.                 and d.depid = @objid
  4922.                 and o.uid = s.uid
  4923.                 and deptype < 2
  4924.  
  4925.     select @found_some = 1
  4926. end
  4927.  
  4928. /*
  4929. **  Did we find anything in sysdepends?
  4930. */
  4931. if @found_some = 0
  4932.     raiserror(15461,-1,-1)
  4933.  
  4934. set nocount off
  4935.  
  4936. return (0) -- sp_depends
  4937. go
  4938.  
  4939. raiserror(15339,-1,-1,'sp_detach_db')
  4940. go
  4941. create procedure sp_detach_db
  4942. @dbname sysname = null,
  4943. @skipchecks nvarchar(10) = null
  4944. as
  4945. declare @dbid int
  4946. declare @exec_stmt nvarchar(540)
  4947.     if @dbname is null
  4948.         begin
  4949.             raiserror(15354,-1,-1)
  4950.             return(1)
  4951.         end
  4952.  
  4953.     if lower(@skipchecks) <> N'true'
  4954.         and lower(@skipchecks) <> N'false'
  4955.         and @skipchecks is not null
  4956.         begin
  4957.             raiserror(15354,-1,-1)
  4958.             return(1)
  4959.         end
  4960.  
  4961.     select @dbid = null
  4962.     select @dbid = dbid from master.dbo.sysdatabases where name=@dbname
  4963.     if @dbid is null
  4964.         begin
  4965.             raiserror(15010,-1,-1,@dbname)
  4966.             return(1)
  4967.         end
  4968.  
  4969.     -- make sure not trying to detach within a transaction
  4970.     if @@trancount > 0
  4971.         begin
  4972.             raiserror(226,-1,-1,'SP_DETACH_DB')
  4973.             return(1)
  4974.         end
  4975.  
  4976.     -- run UPDATE STATISTICS on all tables in the database so they are current
  4977.     -- when transferred to READONLY media
  4978.     if lower(@skipchecks) <> N'true'
  4979.         begin
  4980.             print 'Running UPDATE STATISTICS on all tables'
  4981.             select @exec_stmt = 'USE ' + quotename( @dbname , '[')
  4982.             + ' exec sp_updatestats ''RESAMPLE'' '
  4983.             exec (@exec_stmt)
  4984.         end
  4985.  
  4986.     select @exec_stmt = 'DBCC DETACHDB ('
  4987.             + quotename( @dbname , '[')
  4988.             + ')'
  4989.     exec (@exec_stmt)
  4990.     return (0) -- sp_detach_db
  4991. go
  4992.  
  4993.  
  4994. raiserror(15339,-1,-1,'sp_diskdefault')
  4995. go
  4996. create procedure sp_diskdefault --- 1996/04/08 00:00
  4997. @logicalname    sysname,        /* logical name of the device */
  4998. @defstatus    varchar(15)        /* turn on or off */
  4999. as
  5000.  
  5001. /*
  5002. **  If we're in a transaction, disallow this since it might make recovery
  5003. **  impossible.
  5004. */
  5005. set implicit_transactions off
  5006. if @@trancount > 0
  5007.     begin
  5008.            raiserror(15002,-1,-1,'sp_diskdefault')
  5009.        return (1)
  5010.     end
  5011.  
  5012. /*
  5013. **  Only the SA can run this sproc.
  5014. */
  5015. if not is_srvrolemember('diskadmin') = 1
  5016.     begin
  5017.         raiserror(15247,-1,-1)
  5018.         return (1)
  5019.     end
  5020.  
  5021. /*
  5022. **  Make sure that a device with @logicalname exists.
  5023. */
  5024. if not exists (select * from master.dbo.sysdevices where name = @logicalname)
  5025.     begin
  5026.         raiserror(15012,-1,-1,@logicalname)
  5027.         return (1)
  5028.     end
  5029.  
  5030. /*
  5031. **  Make sure that it is a database disk and not a dump device.
  5032. */
  5033. if exists (select * from master.dbo.sysdevices
  5034.         where name = @logicalname
  5035.             and status & 16 = 16)
  5036.     begin
  5037.         raiserror(15035,-1,-1,@logicalname)
  5038.         return (1)
  5039.     end
  5040.  
  5041. /*
  5042. **  Make sure that the database disk is NOT a RAM device.
  5043. */
  5044. if exists (select *
  5045.         from master.dbo.sysdevices
  5046.         where name = @logicalname
  5047.             and status & 2048 = 2048 )
  5048.     begin
  5049.         raiserror(15139,-1,-1)
  5050.         return (1)
  5051.     end
  5052.  
  5053. if @defstatus = 'defaulton'
  5054.     begin
  5055.         update master.dbo.sysdevices set status = status | 1
  5056.             where name = @logicalname
  5057.         return (0)
  5058.     end
  5059.  
  5060. if @defstatus = 'defaultoff'
  5061.     begin
  5062.         update master.dbo.sysdevices set status = status & ~1
  5063.             where name = @logicalname
  5064.         return (0)
  5065.     end
  5066.  
  5067. /*
  5068. **  @defstatus must be 'defaulton' or 'defaultoff'
  5069. */
  5070. raiserror(15140,-1,-1)
  5071.  
  5072. return (1) -- sp_diskdefault
  5073. go
  5074.  
  5075. checkpoint
  5076. go
  5077.  
  5078.  
  5079. raiserror(15339,-1,-1,'sp_dropdevice')
  5080. go
  5081. create procedure sp_dropdevice --- 1996/04/08 00:00
  5082. @logicalname    sysname,        -- logical name of the device
  5083. @delfile    varchar(7) = null    -- optional param. to delete disk file
  5084. as
  5085.  
  5086.  
  5087. /*
  5088. ** See if user specified something for @delfile and, if so, validate it.
  5089. */
  5090. if @delfile is not null
  5091.     begin
  5092.         select @delfile = lower(@delfile)
  5093.  
  5094.         if @delfile <> 'delfile'
  5095.             begin
  5096.                 raiserror(15216,-1,-1,@delfile)
  5097.                 return(1)
  5098.             end
  5099.     end
  5100.  
  5101. /*
  5102. **  If we're in a transaction, disallow this since it might make recovery
  5103. **  impossible.
  5104. */
  5105. set implicit_transactions off
  5106. if @@trancount > 0
  5107.     begin
  5108.         raiserror(15002,-1,-1,'sp_dropdevice')
  5109.         return (1)
  5110.     end
  5111.  
  5112. /*
  5113. **  Only the system administrator (SA) can run this command.
  5114. **  Check to make sure the executor is the sa.
  5115. */
  5116. if not is_srvrolemember('diskadmin') = 1
  5117.     begin
  5118.         raiserror(15247,-1,-1)
  5119.         return (1)
  5120.     end
  5121.  
  5122. /*
  5123. **  Check and make sure that the device actually exists.
  5124. */
  5125. if not exists (select * from master.dbo.sysdevices where name = @logicalname)
  5126.     begin
  5127.         raiserror(15012,-1,-1,@logicalname)
  5128.         return (1)
  5129.     end
  5130.  
  5131.  
  5132. /*
  5133. ** Drop the device.
  5134. */
  5135.  
  5136. if @delfile = 'delfile'
  5137.     dbcc dbrepair
  5138.     ('', 'dropdevice',@logicalname, 1)  WITH NO_INFOMSGS
  5139. else
  5140.     dbcc dbrepair
  5141.     ('', 'dropdevice',@logicalname, 0)  WITH NO_INFOMSGS
  5142.  
  5143.  
  5144. if @@error <> 0
  5145.     return (1)
  5146.  
  5147. raiserror(15463,-1,-1)
  5148.  
  5149. return (0) -- sp_dropdevice
  5150. go
  5151.  
  5152.  
  5153.  
  5154. raiserror(15339,-1,-1,'sp_dropmessage')
  5155. go
  5156. create procedure sp_dropmessage --- 1996/04/08 00:00
  5157. @msgnum int = null,        -- Number of message to drop.
  5158. @lang sysname = null    -- Language of message to drop (or 'ALL')
  5159. as
  5160. declare @retcode int
  5161. declare @msglangid smallint
  5162.  
  5163.     -- Must be ServerAdmin to manage messages
  5164.     if is_srvrolemember('serveradmin') = 0
  5165.     begin
  5166.         raiserror(15247,-1,-1)
  5167.         return (1)
  5168.     end
  5169.  
  5170. /*
  5171. ** If no message id, show usage
  5172. */
  5173. if @msgnum is null
  5174.     begin
  5175.         raiserror(15177,-1,-1)
  5176.         return (1)
  5177.     end
  5178.  
  5179. /*
  5180. ** Message id must be > 50000
  5181. */
  5182. if @msgnum < 50001
  5183.     begin
  5184.         raiserror(15178,-1,-1)
  5185.         return(1)
  5186.     end
  5187.  
  5188. if (select count(*) from master.dbo.sysmessages where error=@msgnum) = 0
  5189.     begin
  5190.         raiserror(15179,-1,-1,@msgnum)
  5191.         return(1)
  5192.     end
  5193.  
  5194. /*
  5195. ** Verify the language
  5196. */
  5197. if @lang is null
  5198.     select @lang = @@language
  5199. if upper(@lang) <> 'ALL'
  5200. begin
  5201.     begin
  5202.         exec @retcode = sp_validlang @lang
  5203.         if @retcode <>  0
  5204.             return(1)
  5205.     end
  5206.     /*
  5207.     ** Get langid from syslanguages; us_english won't exist, so use 0.
  5208.     */
  5209.     select @msglangid = isnull((select msglangid from master.dbo.syslanguages where name = @lang or alias = @lang),1033)
  5210. end
  5211.  
  5212. /*
  5213. ** The us_english version must be the last one to be dropped
  5214. */
  5215. if (@msglangid = 1033) and (select count(*) from master.dbo.sysmessages where error = @msgnum) > 1
  5216. begin
  5217.     raiserror(15280,-1,-1)
  5218.     return(1)
  5219. end
  5220.  
  5221. /*
  5222. **  Drop the message.
  5223. */
  5224. if upper(@lang) = 'ALL'
  5225.     delete from master.dbo.sysmessages where error = @msgnum
  5226. else
  5227.     delete from master.dbo.sysmessages where error = @msgnum and msglangid = @msglangid
  5228.  
  5229. return (0) -- sp_dropmessage
  5230. go
  5231.  
  5232.  
  5233. raiserror(15339,-1,-1,'sp_droptype')
  5234. go
  5235. create procedure sp_droptype --- 1996/04/08 00:00
  5236. @typename sysname            /* the user type to drop */
  5237. as
  5238.  
  5239. declare @typeid smallint        /* the typeid of the usertype to drop */
  5240.  
  5241. /*
  5242. **  Initialize @typeid so we can tell if we can't find it.
  5243. */
  5244. select @typeid = 0
  5245.  
  5246. /*
  5247. **  Find the user type with @typename.  It must be a user type (xusertype > 256)
  5248. **  and it must be owned by the person (or special role) running the procedure.
  5249. */
  5250. select @typeid = xusertype
  5251.     from systypes
  5252.         where name = @typename and xusertype > 256
  5253.         AND (is_member('db_owner') = 1 OR is_member('db_ddladmin') = 1 OR is_member(user_name(uid))=1)
  5254.  
  5255. if @typeid = 0
  5256.     begin
  5257.         raiserror(15105,-1,-1)
  5258.         return (1)
  5259.     end
  5260.  
  5261. /*
  5262. **  Check to see if the type is being used.  If it is, it can't be dropped.
  5263. */
  5264. if exists (select * from syscolumns where xusertype = @typeid)
  5265.     begin
  5266.         raiserror(15180,-1,-1)
  5267.  
  5268.         /*
  5269.         **  Show where it's being used.
  5270.         */
  5271.         select object = o.name, type = o.xtype, owner = u.name,
  5272.             [column] = c.name, datatype = t.name
  5273.         from syscolumns c, systypes t, sysusers u, sysobjects o
  5274.         where c.xusertype = @typeid
  5275.             and t.xusertype = @typeid
  5276.             and o.uid = u.uid
  5277.             and c.id = o.id
  5278.         order by object, [column]
  5279.  
  5280.         return (1)
  5281.     end
  5282.  
  5283. /*
  5284. **  Everything is consistent so drop the type.
  5285. */
  5286. delete from systypes where xusertype = @typeid
  5287.  
  5288. delete from sysproperties
  5289. where type =  1 and id = 0 and
  5290.     smallid = @typeid
  5291.  
  5292. raiserror(15467,-1,-1)
  5293.  
  5294. return (0) -- sp_droptype
  5295. go
  5296.  
  5297.  
  5298. checkpoint
  5299. go
  5300.  
  5301. raiserror(15339,-1,-1,'sp_dropremotelogin')
  5302. go
  5303. create procedure sp_dropremotelogin --- 1996/04/08 00:00
  5304.     @remoteserver    sysname,        /* name of remote server */
  5305.     @loginame sysname = NULL,        /* user's local user name */
  5306.     @remotename sysname = NULL        /* user's remote name */
  5307. as
  5308.     declare @srvid smallint
  5309.     declare @sid varbinary(85)
  5310.     declare @count int
  5311.  
  5312.     -- DISALLOW USER XACT --
  5313.     set implicit_transactions off
  5314.     if @@trancount > 0
  5315.     begin
  5316.         raiserror(15002,-1,-1,'sp_dropremotelogin')
  5317.         return (1)
  5318.     end
  5319.  
  5320.     -- CHECK PERMISSIONS
  5321.     if not (is_srvrolemember('securityadmin') = 1)
  5322.     begin
  5323.         raiserror(15247,-1,-1)
  5324.         return (1)
  5325.     end
  5326.  
  5327.     -- VALIDATE SERVER NAME --
  5328.     select @srvid = srvid from master.dbo.sysservers where srvname = @remoteserver
  5329.     if @srvid is null
  5330.     begin
  5331.         raiserror(15015,-1,-1,@remoteserver)
  5332.         return (1)
  5333.     end
  5334.  
  5335.     -- CHECK FOR INVALID PARAMETER SYNTAX --
  5336.     if @loginame is null and @remotename is not null
  5337.     begin
  5338.         raiserror(15600,-1,-1,'sp_dropremotelogin')
  5339.         return (1)
  5340.     end
  5341.  
  5342.     -- VALIDATE @loginame --
  5343.     if @loginame is not null
  5344.     begin
  5345.         select @sid = sid from master.dbo.syslogins where loginname = @loginame
  5346.                     AND isntname = 0        -- cannot remap to NT login
  5347.         if @sid is null
  5348.         begin
  5349.             raiserror(15067,-1,-1,@loginame)
  5350.             return (1)
  5351.         end
  5352.     end
  5353.  
  5354.     -- First remove the isrpcinmap bit from all rows which are also outmap
  5355.     update master.dbo.sysxlogins set xstatus = xstatus & ~32    -- isrpcinmap bit
  5356.         where srvid = @srvid AND isrpcinmap = 1 AND ishqoutmap = 1
  5357.             AND ((@sid IS NULL and sid IS NULL) or sid = @sid)
  5358.             AND ((@remotename IS NULL and name IS NULL) or name = @remotename)
  5359.  
  5360.     select @count = @@rowcount
  5361.  
  5362.     -- Delete the remote login(s) - the remaining rows with isrpcinmap set.
  5363.     delete master.dbo.sysxlogins where srvid = @srvid AND isrpcinmap = 1
  5364.             AND ((sid IS NULL and @sid IS NULL) or sid = @sid)
  5365.             AND ((@remotename IS NULL and name IS NULL) or name = @remotename)
  5366.  
  5367.     select @count = @count + @@rowcount
  5368.  
  5369.     -- IF NO ROWS UPDATED OR DELETED, ERROR --
  5370.     if @count = 0
  5371.     begin
  5372.         if (@loginame IS NULL)
  5373.             raiserror(15021,-1,-1,@remoteserver)
  5374.         else if (@remotename IS NULL)
  5375.             raiserror(15027,-1,-1,@loginame,@remoteserver)
  5376.         else
  5377.             raiserror(15185,-1,-1,@remotename,@loginame,@remoteserver)
  5378.         return (1)
  5379.     end
  5380.  
  5381.     -- SUCCESS --
  5382.     return (0)    -- sp_dropremotelogin
  5383. go
  5384.  
  5385.  
  5386. raiserror(15339,-1,-1,'sp_helpconstraint')
  5387. go
  5388. create proc sp_helpconstraint
  5389.     @objname nvarchar(776)            -- the table to check for constraints
  5390.    ,@nomsg   varchar(5) = 'msg'        -- 'nomsg' supresses printing of TBName (sp_help)
  5391. as
  5392.     -- PRELIM
  5393.     set nocount on
  5394.  
  5395.     declare    @objid            int           -- the object id of the table
  5396.             ,@cnstdes        nvarchar(4000)-- string to build up index desc
  5397.             ,@cnstname        sysname       -- name of const. currently under consideration
  5398.             ,@i                int
  5399.             ,@cnstid        int
  5400.             ,@cnsttype        character(2)
  5401.             ,@keys            nvarchar(2126)    --Length (16*max_identifierLength)+(15*2)+(16*3)
  5402.             ,@dbname        sysname
  5403.  
  5404.     -- Create temp table
  5405.     create table #spcnsttab
  5406.     (
  5407.         cnst_id            int            NOT NULL
  5408.         ,cnst_type            nvarchar(146) collate database_default NOT NULL   -- 128 for name + text for DEFAULT
  5409.         ,cnst_name            sysname        collate database_default NOT NULL
  5410.         ,cnst_nonblank_name    sysname        collate database_default NOT NULL
  5411.         ,cnst_2type            character(2)    collate database_default NULL
  5412.         ,cnst_disabled        bit                NULL
  5413.         ,cnst_notrepl        bit                NULL
  5414.         ,cnst_delcasc        bit                NULL
  5415.         ,cnst_updcasc        bit                NULL
  5416.         ,cnst_keys            nvarchar(2126)    collate database_default NULL    -- see @keys above for length descr
  5417.     )
  5418.  
  5419.     -- Check to see that the object names are local to the current database.
  5420.     select @dbname = parsename(@objname,3)
  5421.  
  5422.     if @dbname is not null and @dbname <> db_name()
  5423.     begin
  5424.         raiserror(15250,-1,-1)
  5425.         return (1)
  5426.     end
  5427.  
  5428.     -- Check to see if the table exists and initialize @objid.
  5429.     select @objid = object_id(@objname)
  5430.     if @objid is NULL
  5431.     begin
  5432.         select @dbname=db_name()
  5433.         raiserror(15009,-1,-1,@objname,@dbname)
  5434.         return (1)
  5435.     end
  5436.  
  5437.     -- STATIC CURSOR OVER THE TABLE'S CONSTRAINTS
  5438.     declare ms_crs_cnst cursor local static for
  5439.         select id, xtype, name from sysobjects where parent_obj = @objid
  5440.             and xtype in ('C ','PK','UQ','F ', 'D ')    -- ONLY 6.5 sysconstraints objects
  5441.         for read only
  5442.  
  5443.     -- Now check out each constraint, figure out its type and keys and
  5444.     -- save the info in a temporary table that we'll print out at the end.
  5445.     open ms_crs_cnst
  5446.     fetch ms_crs_cnst into @cnstid ,@cnsttype ,@cnstname
  5447.     while @@fetch_status >= 0
  5448.     begin
  5449.  
  5450.         if @cnsttype in ('PK','UQ')
  5451.         begin
  5452.             -- get indid and index description
  5453.             declare @indid smallint
  5454.             select    @indid = indid,
  5455.                     @cnstdes = case when @cnsttype = 'PK'
  5456.                                 then 'PRIMARY KEY' else 'UNIQUE' end
  5457.                              + case when (status & 16)=16
  5458.                                 then ' (clustered)' else ' (non-clustered)' end
  5459.             from    sysindexes
  5460.             where    name = object_name(@cnstid)
  5461.                     and id = @objid
  5462.  
  5463.             -- Format keys string
  5464.             declare @thiskey nvarchar(131) -- 128+3
  5465.  
  5466.             select @keys = index_col(@objname, @indid, 1), @i = 2
  5467.             if (indexkey_property(@objid, @indid, 1, 'isdescending') = 1)
  5468.                 select @keys = @keys  + '(-)'
  5469.  
  5470.             select @thiskey = index_col(@objname, @indid, @i)
  5471.             if ((@thiskey is not null) and (indexkey_property(@objid, @indid, @i, 'isdescending') = 1))
  5472.                 select @thiskey = @thiskey + '(-)'
  5473.  
  5474.             while (@thiskey is not null)
  5475.             begin
  5476.                 select @keys = @keys + ', ' + @thiskey, @i = @i + 1
  5477.                 select @thiskey = index_col(@objname, @indid, @i)
  5478.                 if ((@thiskey is not null) and (indexkey_property(@objid, @indid, @i, 'isdescending') = 1))
  5479.                     select @thiskey = @thiskey + '(-)'
  5480.             end
  5481.  
  5482.             -- ADD TO TABLE
  5483.             insert into #spcnsttab
  5484.                 (cnst_id,cnst_type,cnst_name, cnst_nonblank_name,cnst_keys, cnst_2type)
  5485.             values (@cnstid, @cnstdes, @cnstname, @cnstname, @keys, @cnsttype)
  5486.         end
  5487.  
  5488.         else
  5489.         if @cnsttype = 'F '
  5490.         begin
  5491.             -- OBTAIN TWO TABLE IDs
  5492.             declare @fkeyid int, @rkeyid int
  5493.             select @fkeyid = fkeyid, @rkeyid = rkeyid from sysreferences where constid = @cnstid
  5494.  
  5495.             -- USE CURSOR OVER FOREIGN KEY COLUMNS TO BUILD COLUMN LISTS
  5496.             --    (NOTE: @keys HAS THE FKEY AND @cnstdes HAS THE RKEY COLUMN LIST)
  5497.             declare ms_crs_fkey cursor local for select fkey, rkey from sysforeignkeys where constid = @cnstid
  5498.             open ms_crs_fkey
  5499.             declare @fkeycol smallint, @rkeycol smallint
  5500.             fetch ms_crs_fkey into @fkeycol, @rkeycol
  5501.             select @keys = col_name(@fkeyid, @fkeycol), @cnstdes = col_name(@rkeyid, @rkeycol)
  5502.             fetch ms_crs_fkey into @fkeycol, @rkeycol
  5503.             while @@fetch_status >= 0
  5504.             begin
  5505.                 select    @keys = @keys + ', ' + col_name(@fkeyid, @fkeycol),
  5506.                         @cnstdes = @cnstdes + ', ' + col_name(@rkeyid, @rkeycol)
  5507.                 fetch ms_crs_fkey into @fkeycol, @rkeycol
  5508.             end
  5509.             deallocate ms_crs_fkey
  5510.  
  5511.             -- ADD ROWS FOR BOTH SIDES OF FOREIGN KEY
  5512.             insert into #spcnsttab
  5513.                 (cnst_id, cnst_type,cnst_name,cnst_nonblank_name,
  5514.                     cnst_keys, cnst_disabled,
  5515.                     cnst_notrepl, cnst_delcasc, cnst_updcasc, cnst_2type)
  5516.             values
  5517.                 (@cnstid, 'FOREIGN KEY', @cnstname, @cnstname,
  5518.                     @keys, ObjectProperty(@cnstid, 'CnstIsDisabled'),
  5519.                     ObjectProperty(@cnstid, 'CnstIsNotRepl'),
  5520.                     ObjectProperty(@cnstid, 'CnstIsDeleteCascade'),
  5521.                     ObjectProperty(@cnstid, 'CnstIsUpdateCascade'),
  5522.                     @cnsttype)
  5523.             insert into #spcnsttab
  5524.                 (cnst_id,cnst_type,cnst_name,cnst_nonblank_name,
  5525.                     cnst_keys,
  5526.                     cnst_2type)
  5527.             select
  5528.                 @cnstid,' ', ' ', @cnstname,
  5529.                     'REFERENCES ' + db_name()
  5530.                         + '.' + rtrim(user_name(ObjectProperty(@rkeyid,'ownerid')))
  5531.                         + '.' + object_name(@rkeyid) + ' ('+@cnstdes + ')',
  5532.                     @cnsttype
  5533.         end
  5534.  
  5535.         else
  5536.         if @cnsttype = 'C '
  5537.         begin
  5538.             select @i = 1
  5539.             select @cnstdes = text from syscomments where id = @cnstid and colid = @i
  5540.             while @cnstdes is not null
  5541.             begin
  5542.                 if @i=1
  5543.                     -- Check constraint
  5544.                     insert into    #spcnsttab
  5545.                         (cnst_id, cnst_type ,cnst_name ,cnst_nonblank_name,
  5546.                             cnst_keys, cnst_disabled, cnst_notrepl, cnst_2type)
  5547.                     select    @cnstid,
  5548.                         case when info = 0 then 'CHECK Table Level '
  5549.                             else 'CHECK on column ' + col_name(@objid ,info) end,
  5550.                         @cnstname ,@cnstname ,substring(@cnstdes,1,2000),
  5551.                         ObjectProperty(@cnstid, 'CnstIsDisabled'),
  5552.                         ObjectProperty(@cnstid, 'CnstIsNotRepl'),
  5553.                         @cnsttype
  5554.                     from sysobjects    where id = @cnstid
  5555.                 else
  5556.                     insert into #spcnsttab (cnst_id,cnst_type,cnst_name,cnst_nonblank_name,cnst_keys, cnst_2type)
  5557.                     select    @cnstid,' ' ,' ' ,@cnstname ,substring(@cnstdes,1,2000), @cnsttype
  5558.  
  5559.                 if len(@cnstdes) > 2000
  5560.                     insert into #spcnsttab (cnst_id,cnst_type,cnst_name,cnst_nonblank_name,cnst_keys, cnst_2type)
  5561.                     select    @cnstid,' ' ,' ' ,@cnstname ,substring(@cnstdes,2001,2000), @cnsttype
  5562.  
  5563.                 select @cnstdes = null
  5564.                 select @i = @i + 1
  5565.                 select @cnstdes = text from syscomments where id = @cnstid and colid = @i
  5566.             end
  5567.         end
  5568.  
  5569.         else
  5570.         if (@cnsttype = 'D ')
  5571.         begin
  5572.             select @i = 1
  5573.             select @cnstdes = text from syscomments where id = @cnstid and colid = @i
  5574.             while @cnstdes is not null
  5575.             begin
  5576.                 if @i=1
  5577.                     insert into    #spcnsttab
  5578.                         (cnst_id,cnst_type ,cnst_name ,cnst_nonblank_name ,cnst_keys, cnst_2type)
  5579.                     select @cnstid, 'DEFAULT on column ' + col_name(@objid ,info),
  5580.                         @cnstname ,@cnstname ,substring(@cnstdes,1,2000), @cnsttype
  5581.                     from sysobjects where id = @cnstid
  5582.                 else
  5583.                     insert into #spcnsttab (cnst_id,cnst_type,cnst_name,cnst_nonblank_name,cnst_keys, cnst_2type)
  5584.                     select    @cnstid,' ' ,' ' ,@cnstname ,substring(@cnstdes,1,2000), @cnsttype
  5585.  
  5586.                 if len(@cnstdes) > 2000
  5587.                     insert into #spcnsttab (cnst_id,cnst_type,cnst_name,cnst_nonblank_name,cnst_keys, cnst_2type)
  5588.                     select    @cnstid,' ' ,' ' ,@cnstname ,substring(@cnstdes,2001,2000), @cnsttype
  5589.  
  5590.                 select @i = @i + 1
  5591.                 select @cnstdes = null
  5592.                 select @cnstdes = text from syscomments where id = @cnstid and colid = @i
  5593.             end
  5594.         end
  5595.  
  5596.         fetch ms_crs_cnst into @cnstid ,@cnsttype ,@cnstname
  5597.     end        --of major loop
  5598.     deallocate ms_crs_cnst
  5599.  
  5600.     -- Find any rules or defaults bound by the sp_bind... method.
  5601.     insert into #spcnsttab (cnst_id,cnst_type,cnst_name,cnst_nonblank_name,cnst_keys, cnst_2type)
  5602.     select c.domain,'RULE on column ' + c.name + ' (bound with sp_bindrule)',
  5603.         object_name(c.domain), object_name(c.domain), text, 'R '
  5604.     from    syscolumns c, syscomments m
  5605.     where    c.id = @objid and m.id = c.domain and ObjectProperty(c.domain, 'IsRule') = 1
  5606.  
  5607.     insert into #spcnsttab (cnst_id,cnst_type,cnst_name,cnst_nonblank_name,cnst_keys, cnst_2type)
  5608.     select c.cdefault, 'DEFAULT on column ' + c.name + ' (bound with sp_bindefault)',
  5609.         object_name(c.cdefault),object_name(c.cdefault), text, 'D '
  5610.     from    syscolumns c,syscomments m
  5611.     where    c.id = @objid and m.id = c.cdefault and ObjectProperty(c.cdefault, 'IsConstraint') = 0
  5612.  
  5613.  
  5614.     -- OUTPUT RESULTS: FIRST THE OBJECT NAME (if not suppressed)
  5615.     if @nomsg <> 'nomsg'
  5616.     begin
  5617.         select 'Object Name' = @objname
  5618.         print ' '
  5619.     end
  5620.  
  5621.     -- Now print out the contents of the temporary index table.
  5622.     if exists (select * from #spcnsttab)
  5623.         select
  5624.             'constraint_type' = cnst_type,
  5625.             'constraint_name' = cnst_name,
  5626.             'delete_action'=
  5627.                     CASE
  5628.                         When cnst_name = ' ' Then ' '
  5629.                         When cnst_2type in ('F ') Then
  5630.                             CASE When cnst_delcasc = 1
  5631.                                 Then 'Cascade' else 'No Action' end
  5632.                         Else '(n/a)'
  5633.                     END,
  5634.             'update_action'=
  5635.                     CASE
  5636.                         When cnst_name = ' ' Then ' '
  5637.                         When cnst_2type in ('F ') Then
  5638.                             CASE When cnst_updcasc = 1
  5639.                                 Then 'Cascade' else 'No Action' end
  5640.                         Else '(n/a)'
  5641.                     END,
  5642.             'status_enabled' =
  5643.                     CASE
  5644.                         When cnst_name = ' ' Then ' '
  5645.                         When cnst_2type in ('F ','C ') Then
  5646.                             CASE When cnst_disabled = 1
  5647.                                 then 'Disabled' else 'Enabled' end
  5648.                         Else '(n/a)'
  5649.                     END,
  5650.             'status_for_replication' =
  5651.                     CASE
  5652.                         When cnst_name = ' ' Then ' '
  5653.                         When cnst_2type in ('F ','C ') Then
  5654.                             CASE When cnst_notrepl = 1
  5655.                                 Then 'Not_For_Replication' else 'Is_For_Replication' end
  5656.                         Else '(n/a)'
  5657.                     END,
  5658.             'constraint_keys' = cnst_keys
  5659.         from #spcnsttab order by cnst_nonblank_name ,cnst_name desc
  5660.     else
  5661.         raiserror(15469,-1,-1) --'No constraints have been defined for this object.'
  5662.  
  5663.     print ' '
  5664.  
  5665.     if exists (select * from sysreferences where rkeyid = @objid)
  5666.         select
  5667.             'Table is referenced by foreign key' =
  5668.                 db_name() + '.'
  5669.                     + rtrim(user_name(ObjectProperty(fkeyid,'ownerid')))
  5670.                     + '.' + object_name(fkeyid)
  5671.                     + ': ' + object_name(constid)
  5672.             from sysreferences where rkeyid = @objid order by 1
  5673.     else
  5674.         raiserror(15470,-1,-1) --'No foreign keys reference this table.'
  5675.  
  5676.     return (0) -- sp_helpconstraint
  5677. go
  5678.  
  5679. checkpoint
  5680. go
  5681.  
  5682. raiserror(15339,-1,-1,'system_function_schema.fn_dblog')
  5683. go
  5684. create function system_function_schema.fn_dblog
  5685.     (
  5686.         @start nvarchar (22) = NULL,
  5687.         @end   nvarchar (22) = NULL
  5688.     )
  5689.  
  5690. returns table
  5691. as
  5692.     return select * from OpenRowset (DBLog, @start, @end)
  5693. go
  5694.  
  5695. raiserror(15339,-1,-1,'system_function_schema.fn_helpcollations')
  5696. go
  5697. create function system_function_schema.fn_helpcollations
  5698.     (
  5699.     )
  5700.  
  5701. returns @tab table(name sysname NOT NULL,
  5702.     description    nvarchar(1000)    NOT NULL)
  5703. as
  5704. begin
  5705.     insert @tab
  5706.     select * from OpenRowset(collations)
  5707.  
  5708.     return
  5709. end -- fn_helpcollations
  5710. go
  5711.  
  5712. raiserror(15339,-1,-1,'system_function_schema.fn_trace_getinfo')
  5713. go
  5714. create function system_function_schema.fn_trace_getinfo
  5715.     (@handle int = 0
  5716.     )
  5717.  
  5718. returns @tab table(traceid int NOT NULL,
  5719.     property int NOT NULL,
  5720.     value sql_variant)
  5721. as
  5722. begin
  5723.     insert @tab
  5724.     select * from OpenRowset(TraceInfo, @handle)
  5725.  
  5726.     return
  5727. end -- fn_trace_getinfo
  5728. go
  5729.  
  5730. raiserror(15339,-1,-1,'system_function_schema.fn_trace_geteventinfo')
  5731. go
  5732. create function system_function_schema.fn_trace_geteventinfo
  5733.     (@handle int
  5734.     )
  5735.  
  5736. returns @tab table(eventid int NOT NULL,
  5737.     columnid int NOT NULL)
  5738. as
  5739. begin
  5740.     insert @tab
  5741.     select * from OpenRowset(TraceEventInfo, @handle)
  5742.  
  5743.     return
  5744. end -- fn_trace_geteventinfo
  5745. go
  5746.  
  5747. raiserror(15339,-1,-1,'system_function_schema.fn_trace_getfilterinfo')
  5748. go
  5749. create function system_function_schema.fn_trace_getfilterinfo
  5750.     (@handle int = 0
  5751.     )
  5752.  
  5753. returns @tab table(columnid int NOT NULL,
  5754.     logical_operator int NOT NULL,
  5755.     comparison_operator int NOT NULL,
  5756.     value sql_variant)
  5757. as
  5758. begin
  5759.     insert @tab
  5760.     select * from OpenRowset(TraceFilterInfo, @handle)
  5761.  
  5762.     return
  5763. end -- fn_trace_getfilterinfo
  5764. go
  5765.  
  5766.  
  5767. raiserror(15339,-1,-1,'system_function_schema.fn_trace_gettable')
  5768. go
  5769. create function system_function_schema.fn_trace_gettable
  5770.     (@filename nvarchar(256), 
  5771.      @numfiles int = -1)
  5772.      
  5773. returns table as
  5774. return select * from OpenRowset(TrcTable, @filename, @numfiles)
  5775. go
  5776.  
  5777.  
  5778. raiserror(15339,-1,-1,'system_function_schema.fn_servershareddrives')
  5779. go
  5780. create function system_function_schema.fn_servershareddrives
  5781.     (
  5782.     )
  5783.  
  5784. returns @tab table(DriveName nchar(1) NOT NULL)
  5785. as
  5786. begin
  5787.     insert @tab
  5788.     select * from OpenRowset(servershareddrives)
  5789.  
  5790.     return
  5791. end -- fn_servershareddrives
  5792. go
  5793.  
  5794. raiserror(15339,-1,-1,'system_function_schema.fn_virtualfilestats')
  5795. go
  5796. create function system_function_schema.fn_virtualfilestats
  5797.     (
  5798.     @DatabaseId Int = -1,
  5799.     @FileId Int = -1
  5800.     )
  5801.  
  5802. returns @tab table(DbId SmallInt NOT NULL, FileId SmallInt NOT NULL, TimeStamp Int NOT NULL,
  5803.         NumberReads BigInt NOT NULL, NumberWrites BigInt NOT NULL, BytesRead BigInt NOT NULL,
  5804.         BytesWritten BigInt NOT NULL, IoStallMS BigInt NOT NULL )
  5805. as
  5806. begin
  5807.     insert @tab
  5808.     select * from OpenRowset(VirtualFileStats, @DatabaseId, @FileId)
  5809.  
  5810.     return
  5811. end -- fn_virtualfilestats
  5812. go
  5813.  
  5814. raiserror(15339,-1,-1,'system_function_schema.fn_virtualservernodes')
  5815. go
  5816. create function system_function_schema.fn_virtualservernodes
  5817.     (
  5818.     )
  5819.  
  5820. returns @tab table(NodeName sysname NOT NULL)
  5821. as
  5822. begin
  5823.     insert @tab
  5824.     select * from OpenRowset(virtualservernodes)
  5825.  
  5826.     return
  5827. end -- fn_virtualservernodes
  5828. go
  5829.  
  5830. raiserror(15339,-1,-1,'system_function_schema.fn_get_sql')
  5831. go
  5832. create function system_function_schema.fn_get_sql
  5833.     (
  5834.     @handle binary(20)
  5835.     )
  5836. returns @tab table(dbid SmallInt,
  5837.     objectid Int,
  5838.     number SmallInt,
  5839.     encrypted Bit NOT NULL,
  5840.     text Text)
  5841. as
  5842. begin
  5843.     insert @tab
  5844.     select * from OpenRowset(FnGetSql, @handle)
  5845.  
  5846.     return
  5847. end -- fn_get_sql
  5848. go
  5849.  
  5850. raiserror(15339,-1,-1,'sp_helpdb')
  5851. go
  5852. create procedure sp_helpdb  --- 1995/12/20 15:34 #12755
  5853. @dbname sysname = NULL            /* database name to change */
  5854. as
  5855.  
  5856. declare @exec_stmt nvarchar(625)
  5857. declare @showdev    bit
  5858. declare @name           sysname
  5859. declare @cmd    nvarchar(279)
  5860. declare @low nvarchar(11)
  5861. declare @dbdesc varchar(600)    /* the total description for the db */
  5862. declare @propdesc varchar(40)
  5863.  
  5864. set nocount on
  5865.  
  5866. /*    Create temp table before any DMP to enure dynamic
  5867. **  Since we examine the status bits in sysdatabase and turn them
  5868. **  into english, we need a temporary table to build the descriptions.
  5869. */
  5870. create table #spdbdesc
  5871. (
  5872.     dbname sysname,
  5873.     owner sysname,
  5874.     created nvarchar(11),
  5875.     dbid    smallint,
  5876.     dbdesc    nvarchar(600)    null,
  5877.     dbsize        nvarchar(13) null,
  5878.     cmptlevel    tinyint
  5879. )
  5880.  
  5881.  
  5882. /*
  5883. **  If no database name given, get 'em all.
  5884. */
  5885. if @dbname is null
  5886.     select @showdev = 0
  5887. else select @showdev = 1
  5888.  
  5889. /*
  5890. **  See if the database exists
  5891. */
  5892. if not exists (select * from master.dbo.sysdatabases
  5893.     where (@dbname is null or name = @dbname))
  5894.     begin
  5895.         raiserror(15010,-1,-1,@dbname)
  5896.       return (1)
  5897.     end
  5898.  
  5899. select @low = convert(varchar(11),low) from master.dbo.spt_values
  5900.             where type = N'E' and number = 1
  5901. /*
  5902. **  Initialize #spdbdesc from sysdatabases
  5903. */
  5904. insert into #spdbdesc (dbname, owner, created, dbid, cmptlevel)
  5905.         select name, suser_sname(sid), convert(nvarchar(11), crdate),
  5906.             dbid, cmptlevel from master.dbo.sysdatabases
  5907.             where (@dbname is null or name = @dbname)
  5908.  
  5909. /*
  5910. ** Check if you have access to database
  5911. ** if have access set size and collation
  5912. */
  5913. select @low = convert(varchar(11),low) from master.dbo.spt_values
  5914.             where type = N'E' and number = 1
  5915.  
  5916. declare ms_crs_c1 cursor for
  5917.     select db_name (dbid) from #spdbdesc
  5918. open ms_crs_c1
  5919. fetch ms_crs_c1 into @name
  5920. while @@fetch_status >= 0
  5921. begin
  5922.     if (has_dbaccess(@name) <> 1)
  5923.     begin
  5924.       delete #spdbdesc where current of ms_crs_c1
  5925.       raiserror(15622,-1,-1, @name)
  5926.     end
  5927.     else
  5928.         begin
  5929.             /* Insert row for each database */
  5930.             select @exec_stmt = 'update #spdbdesc
  5931.                                 set dbsize = (select str(convert(dec(15),sum(size))* ' + @low + '/ 1048576,10,2)+ N'' MB'' from '
  5932.                                  + quotename(@name, N'[') + N'.dbo.sysfiles) WHERE current of ms_crs_c1'
  5933.  
  5934.             execute (@exec_stmt)
  5935.         end
  5936.     fetch ms_crs_c1 into @name
  5937. end
  5938. deallocate ms_crs_c1
  5939.  
  5940. /*
  5941. **  Now for each dbid in #spdbdesc, build the database status
  5942. **  description.
  5943. */
  5944. declare @curdbid smallint    /* the one we're currently working on */
  5945. /*
  5946. **  Set @curdbid to the first dbid.
  5947. */
  5948. select @curdbid = min(dbid) from #spdbdesc
  5949.  
  5950.  
  5951. while @curdbid IS NOT NULL
  5952. begin
  5953.     set @name = db_name(@curdbid)
  5954.  
  5955.     -- These properties always available
  5956.     SELECT @dbdesc = 'Status=' + convert(sysname,DatabasePropertyEx(@name,'Status'))
  5957.     SELECT @dbdesc = @dbdesc + ', Updateability=' + convert(sysname,DatabasePropertyEx(@name,'Updateability'))
  5958.     SELECT @dbdesc = @dbdesc + ', UserAccess=' + convert(sysname,DatabasePropertyEx(@name,'UserAccess'))
  5959.     SELECT @dbdesc = @dbdesc + ', Recovery=' + convert(sysname,DatabasePropertyEx(@name,'Recovery'))
  5960.     SELECT @dbdesc = @dbdesc + ', Version=' + convert(sysname,DatabasePropertyEx(@name,'Version'))
  5961.  
  5962.     -- These props only available if db not shutdown
  5963.     IF DatabaseProperty(@name, 'IsShutdown') = 0
  5964.     BEGIN
  5965.         SELECT @dbdesc = @dbdesc + ', Collation=' + convert(sysname,DatabasePropertyEx(@name,'Collation'))
  5966.         SELECT @dbdesc = @dbdesc + ', SQLSortOrder=' + convert(sysname,DatabasePropertyEx(@name,'SQLSortOrder'))
  5967.     END
  5968.  
  5969.     -- These are the boolean properties
  5970.     IF DatabasePropertyEx(@name,'IsAutoClose') = 1
  5971.         SELECT @dbdesc = @dbdesc + ', ' + 'IsAutoClose'
  5972.     IF DatabasePropertyEx(@name,'IsAutoShrink') = 1
  5973.         SELECT @dbdesc = @dbdesc + ', ' + 'IsAutoShrink'
  5974.     IF DatabasePropertyEx(@name,'IsInStandby') = 1
  5975.         SELECT @dbdesc = @dbdesc + ', ' + 'IsInStandby'
  5976.     IF DatabasePropertyEx(@name,'IsTornPageDetectionEnabled') = 1
  5977.         SELECT @dbdesc = @dbdesc + ', ' + 'IsTornPageDetectionEnabled'
  5978.     IF DatabasePropertyEx(@name,'IsAnsiNullDefault') = 1
  5979.         SELECT @dbdesc = @dbdesc + ', ' + 'IsAnsiNullDefault'
  5980.     IF DatabasePropertyEx(@name,'IsAnsiNullsEnabled') = 1
  5981.         SELECT @dbdesc = @dbdesc + ', ' + 'IsAnsiNullsEnabled'
  5982.     IF DatabasePropertyEx(@name,'IsAnsiPaddingEnabled') = 1
  5983.         SELECT @dbdesc = @dbdesc + ', ' + 'IsAnsiPaddingEnabled'
  5984.     IF DatabasePropertyEx(@name,'IsAnsiWarningsEnabled') = 1
  5985.         SELECT @dbdesc = @dbdesc + ', ' + 'IsAnsiWarningsEnabled'
  5986.     IF DatabasePropertyEx(@name,'IsArithmeticAbortEnabled') = 1
  5987.         SELECT @dbdesc = @dbdesc + ', ' + 'IsArithmeticAbortEnabled'
  5988.     IF DatabasePropertyEx(@name,'IsAutoCreateStatistics') = 1
  5989.         SELECT @dbdesc = @dbdesc + ', ' + 'IsAutoCreateStatistics'
  5990.     IF DatabasePropertyEx(@name,'IsAutoUpdateStatistics') = 1
  5991.         SELECT @dbdesc = @dbdesc + ', ' + 'IsAutoUpdateStatistics'
  5992.     IF DatabasePropertyEx(@name,'IsCloseCursorsOnCommitEnabled') = 1
  5993.         SELECT @dbdesc = @dbdesc + ', ' + 'IsCloseCursorsOnCommitEnabled'
  5994.     IF DatabasePropertyEx(@name,'IsFullTextEnabled') = 1
  5995.         SELECT @dbdesc = @dbdesc + ', ' + 'IsFullTextEnabled'
  5996.     IF DatabasePropertyEx(@name,'IsLocalCursorsDefault') = 1
  5997.         SELECT @dbdesc = @dbdesc + ', ' + 'IsLocalCursorsDefault'
  5998.     IF DatabasePropertyEx(@name,'IsNullConcat') = 1
  5999.         SELECT @dbdesc = @dbdesc + ', ' + 'IsNullConcat'
  6000.     IF DatabasePropertyEx(@name,'IsNumericRoundAbortEnabled') = 1
  6001.         SELECT @dbdesc = @dbdesc + ', ' + 'IsNumericRoundAbortEnabled'
  6002.     IF DatabasePropertyEx(@name,'IsQuotedIdentifiersEnabled') = 1
  6003.         SELECT @dbdesc = @dbdesc + ', ' + 'IsQuotedIdentifiersEnabled'
  6004.     IF DatabasePropertyEx(@name,'IsRecursiveTriggersEnabled') = 1
  6005.         SELECT @dbdesc = @dbdesc + ', ' + 'IsRecursiveTriggersEnabled'
  6006.     IF DatabasePropertyEx(@name,'IsMergePublished') = 1
  6007.         SELECT @dbdesc = @dbdesc + ', ' + 'IsMergePublished'
  6008.     IF DatabasePropertyEx(@name,'IsPublished') = 1
  6009.         SELECT @dbdesc = @dbdesc + ', ' + 'IsPublished'
  6010.     IF DatabasePropertyEx(@name,'IsSubscribed') = 1
  6011.         SELECT @dbdesc = @dbdesc + ', ' + 'IsSubscribed'
  6012.     IF DatabasePropertyEx(@name,'IsSyncWithBackup') = 1
  6013.         SELECT @dbdesc = @dbdesc + ', ' + 'IsSyncWithBackup'
  6014.  
  6015.     update #spdbdesc set dbdesc = @dbdesc where dbid = @curdbid
  6016.  
  6017.     /*
  6018.     **  Now get the next, if any dbid.
  6019.     */
  6020.     select @curdbid = min(dbid) from #spdbdesc where dbid > @curdbid
  6021. end
  6022.  
  6023. /*
  6024. **  Now #spdbdesc is complete so we can print out the db info
  6025. */
  6026. select name = dbname,
  6027.     db_size = dbsize,
  6028.     owner = owner,
  6029.     dbid = dbid,
  6030.     created = created,
  6031.     status = dbdesc,
  6032.     compatibility_level = cmptlevel
  6033. from  #spdbdesc
  6034. order by dbname
  6035.  
  6036. /*
  6037. **  If we are looking at one database, show its file allocation.
  6038. */
  6039. if @showdev = 1 and has_dbaccess(@dbname) = 1
  6040. begin
  6041.     print N' '
  6042.     select @cmd = N'use ' +  quotename(@dbname) + N' exec sp_helpfile'
  6043.     exec (@cmd)
  6044.  
  6045. end
  6046. return (0) -- sp_helpdb
  6047. go
  6048.  
  6049. raiserror(15339,-1,-1,'sp_helpdevice')
  6050. go
  6051. create procedure sp_helpdevice --- 1996/04/08 00:00
  6052. @devname sysname = NULL        /* device to check out */
  6053. as
  6054.  
  6055. /*    Create temp tables before any DML to ensure dynamic
  6056. **  Create a temporary table where we can build up a translation of
  6057. **  the device status bits.
  6058. */
  6059. create table #spdevtab
  6060. (
  6061.     name sysname        NOT NULL,
  6062.     statusdesc nvarchar(255)    null
  6063. )
  6064. /*
  6065. **  See if the device exists.
  6066. */
  6067.  
  6068. if not exists (select * from master.dbo.sysdevices where
  6069.     (@devname is null or name = @devname))
  6070.     begin
  6071.         raiserror(15012,-1,-1,@devname)
  6072.         return (1)
  6073.     end
  6074.  
  6075. set nocount on
  6076.  
  6077. /*
  6078. **  Initialize the temporary table with the names of the devices.
  6079. */
  6080. insert into #spdevtab (name)
  6081.     select name
  6082.         from master.dbo.sysdevices
  6083.         where (@devname is null or name = @devname)
  6084.  
  6085.  
  6086. /*
  6087. **  Now figure out what kind of controller type it is.
  6088. **
  6089. **  cntrltype =            0    special (data disk)
  6090. **                2    disk (dump)
  6091. **                3-4    floppy (dump)    Not supported in SQL 7.0
  6092. **                5    tape            No size information in SQL 7.0
  6093. **                6    pipe
  6094. **                7    virtual_device
  6095. */
  6096. update #spdevtab
  6097.     set statusdesc = N'special'
  6098.         from master.dbo.sysdevices d, #spdevtab
  6099.             where d.cntrltype = 0
  6100.                 and #spdevtab.name = d.name
  6101. update #spdevtab
  6102.     set statusdesc = N'disk'
  6103.         from master.dbo.sysdevices d, #spdevtab
  6104.             where d.cntrltype = 2
  6105.                 and #spdevtab.name = d.name
  6106.  
  6107. update #spdevtab
  6108.     set statusdesc = N'tape'
  6109.         from master.dbo.sysdevices d, #spdevtab
  6110.             where d.cntrltype = 5
  6111.                 and #spdevtab.name = d.name
  6112.  
  6113. update #spdevtab
  6114.     set statusdesc = N'pipe'
  6115.         from master.dbo.sysdevices d, #spdevtab
  6116.             where d.cntrltype = 6
  6117.                 and #spdevtab.name = d.name
  6118. update #spdevtab
  6119.     set statusdesc = N'virtual_device'
  6120.         from master.dbo.sysdevices d, #spdevtab
  6121.             where d.cntrltype = 7
  6122.                 and #spdevtab.name = d.name
  6123.  
  6124. update #spdevtab
  6125.     set statusdesc = N'UNKNOWN DEVICE'
  6126.         from master.dbo.sysdevices d, #spdevtab
  6127.             where d.cntrltype >= 8
  6128.                 and #spdevtab.name = d.name
  6129.  
  6130.  
  6131. /*
  6132. **  Now check out the status bits and turn them into english.
  6133. **  Status of 16 is a dump device.
  6134. */
  6135. update #spdevtab set statusdesc = statusdesc + N', ' + rtrim(v.name)
  6136.     from master.dbo.sysdevices d, master.dbo.spt_values v, #spdevtab
  6137.     where v.type = 'V' and v.number > -1
  6138.         and d.status & v.number = 16
  6139.         and #spdevtab.name = d.name
  6140.  
  6141. /*
  6142. **  Status of 1 is a default disk.
  6143. */
  6144. update #spdevtab set statusdesc = statusdesc + N', ' + rtrim(v.name)
  6145.     from master.dbo.sysdevices d, master.dbo.spt_values v, #spdevtab
  6146.     where v.type = 'V' and v.number > -1
  6147.         and d.status & v.number = 1
  6148.         and #spdevtab.name = d.name
  6149.  
  6150. /*
  6151. **  Status of 2 is a physical disk.
  6152. */
  6153. update #spdevtab
  6154.     set statusdesc = substring(statusdesc, 1, 225) + N', ' + rtrim(v.name)
  6155.     from master.dbo.sysdevices d, master.dbo.spt_values v, #spdevtab
  6156.     where v.type = 'V' and v.number > -1
  6157.         and d.status & v.number = 2
  6158.         and #spdevtab.name = d.name
  6159.  
  6160. /*
  6161. **  Add in its size in MB.
  6162. */
  6163. update #spdevtab
  6164.     set statusdesc = statusdesc + N', ' + convert(varchar(10),
  6165.         round((convert(float, d.size) * (select low from master.dbo.spt_values
  6166.             where type = 'E' and number = 1)
  6167.              / 1048576), 1)) + ' MB'
  6168.     from master.dbo.sysdevices d, #spdevtab, master.dbo.spt_values v
  6169.     where d.status & 2 = 2
  6170.         and #spdevtab.name = d.name
  6171.         and v.number = 1
  6172.         and v.type = 'E'
  6173.  
  6174. /*
  6175. **  Status of 4 is a logical disk.
  6176. */
  6177. update #spdevtab
  6178.     set statusdesc = substring(statusdesc, 1, 225) + N', ' + rtrim(v.name)
  6179.     from master.dbo.sysdevices d, master.dbo.spt_values v, #spdevtab
  6180.     where v.type = 'V' and v.number > -1
  6181.         and d.status & v.number = 4
  6182.         and #spdevtab.name = d.name
  6183.  
  6184. /*
  6185. **  Status of 8 is a skip tape header.
  6186. */
  6187. update #spdevtab
  6188.     set statusdesc = substring(statusdesc, 1, 225) + N', ' + rtrim(v.name)
  6189.     from master.dbo.sysdevices d, master.dbo.spt_values v, #spdevtab
  6190.     where v.type = 'V' and v.number > -1
  6191.         and d.status & v.number = 8
  6192.         and #spdevtab.name = d.name
  6193. /*
  6194. **  Status of 4096 is read only.
  6195. */
  6196. update #spdevtab
  6197.     set statusdesc = substring(statusdesc, 1, 225) + N', ' + rtrim(v.name)
  6198.     from master.dbo.sysdevices d, master.dbo.spt_values v, #spdevtab
  6199.     where v.type = 'V' and v.number > -1
  6200.         and d.status & v.number = 4096
  6201.         and #spdevtab.name = d.name
  6202. /*
  6203. **  Status of 8192 is deferred.
  6204. */
  6205. update #spdevtab
  6206.     set statusdesc = substring(statusdesc, 1, 225) + N', ' + (v.name)
  6207.     from master.dbo.sysdevices d, master.dbo.spt_values v, #spdevtab
  6208.     where v.type = 'V' and v.number > -1
  6209.         and d.status & v.number = 8192
  6210.         and #spdevtab.name = d.name
  6211.  
  6212. set nocount off
  6213.  
  6214. /*
  6215. **  The device number is in the high byte of sysdevices.low so
  6216. **  spt_values tells us which byte to pick out.
  6217. */
  6218. select device_name = d.name, physical_name = d.phyname,
  6219.     description = #spdevtab.statusdesc,
  6220.     status = d.status&12319, d.cntrltype,
  6221.     size
  6222.     from master.dbo.sysdevices d, #spdevtab, master.dbo.spt_values v
  6223.     where d.name = #spdevtab.name
  6224.         and v.type = 'E'
  6225.         and v.number = 3
  6226.  
  6227. return(0) -- sp_helpdevice
  6228. go
  6229.  
  6230. raiserror(15339,-1,-1,'sp_helpfile')
  6231. go
  6232. create procedure sp_helpfile
  6233. @filename sysname = NULL            /* file name or all files */
  6234. as
  6235.  
  6236. set nocount on
  6237.  
  6238. if @filename IS NULL
  6239. begin
  6240. select     name,  fileid, filename,
  6241.     filegroup = filegroup_name(groupid),
  6242.     'size' = convert(nvarchar(15), size * 8) + N' KB',
  6243.     'maxsize' = (case maxsize when -1 then N'Unlimited'
  6244.             else
  6245.             convert(nvarchar(15), maxsize * 8) + N' KB' end),
  6246.     'growth' = (case status & 0x100000 when 0x100000 then
  6247.         convert(nvarchar(3), growth) + N'%'
  6248.         else
  6249.         convert(nvarchar(15), growth * 8) + N' KB' end),
  6250.     'usage' = (case status & 0x40 when 0x40 then 'log only' else 'data only' end)
  6251.     from sysfiles
  6252.     order by fileid
  6253.  
  6254. end
  6255. else
  6256. begin
  6257.     if file_id(@filename) IS NULL
  6258.     begin -- no such file
  6259.         raiserror (15325, -1, -1, 'file', @filename)
  6260.         return (1)
  6261.     end
  6262.     select     name,  filename,
  6263.     filegroup = filegroup_name(groupid),
  6264.     'size' = convert(nvarchar(15), size * 8) + N' KB',
  6265.     'maxsize' = (case maxsize when -1 then N'Unlimited'
  6266.             else
  6267.             convert(nvarchar(15), maxsize * 8) + N' KB' end),
  6268.     'growth' = (case status & 0x100000 when 0x100000 then
  6269.         convert(nvarchar(3), growth) + N'%'
  6270.         else
  6271.         convert(nvarchar(15), growth * 8) + N' KB' end),
  6272.     'usage' = (case status & 0x40 when 0x40 then 'log only' else 'data only' end)
  6273.     from sysfiles
  6274.     where fileid = file_id(@filename)
  6275.     order by fileid
  6276. end
  6277.  
  6278. return (0) -- sp_helpfile
  6279. go
  6280.  
  6281. raiserror(15339,-1,-1,'sp_helpfilegroup')
  6282. go
  6283. create procedure sp_helpfilegroup
  6284. @filegroupname sysname = NULL        /* filegroup name or all filegroups */
  6285. as
  6286.  
  6287. set nocount on
  6288. -- status & 0x40 is a log file and thus not in any filegroup
  6289. if @filegroupname IS NULL
  6290. begin
  6291.     select     g.groupname,  g.groupid, 'filecount' =
  6292.         (select count(*) from sysfiles f
  6293.             where f.groupid = g.groupid
  6294.                 and (f.status & 0x40 <> 0x40))
  6295.     from sysfilegroups g
  6296. end
  6297. else
  6298. begin
  6299.     if (filegroup_id(@filegroupname) IS NULL)
  6300.     begin
  6301.         raiserror (15325, -1, -1, 'filegroup', @filegroupname)
  6302.         return (1)
  6303.     end
  6304.     select     g.groupname,  g.groupid, 'filecount' =
  6305.         (select count(*) from sysfiles f
  6306.             where f.groupid = g.groupid
  6307.                 and (f.status & 0x40 <> 0x40))
  6308.     from sysfilegroups g
  6309.     where g.groupid = filegroup_id(@filegroupname)
  6310.  
  6311.     select     'file_in_group' = name,  fileid, filename,
  6312.     'size' = convert(nvarchar(15), size * 8) + N' KB',
  6313.     'maxsize' = (case maxsize when -1 then N'Unlimited'
  6314.             else
  6315.             convert(nvarchar(15), maxsize * 8) + N' KB' end),
  6316.     'growth' = (case status & 0x100000 when 0x100000 then
  6317.         convert(nvarchar(3), growth) + N'%'
  6318.         else
  6319.         convert(nvarchar(15), growth * 8) + N' KB' end)
  6320.     from sysfiles
  6321.     where groupid = filegroup_id(@filegroupname)
  6322.     and (status & 0x40 <> 0x40)
  6323.     order by fileid
  6324. end
  6325.  
  6326. return (0) -- sp_helpfilegroup
  6327. go
  6328.  
  6329.  
  6330. raiserror(15339,-1,-1,'sp_helpgroup')
  6331. go
  6332. create procedure sp_helpgroup --- 1996/04/08 00:00
  6333. @grpname sysname = NULL        /* group name of interest */
  6334. as
  6335.  
  6336. /*
  6337. **  If no group name given, list all the groups.
  6338. */
  6339. if @grpname is null
  6340. begin
  6341.     select Group_name = name, Group_id = uid
  6342.         from sysusers
  6343.             where (issqlrole = 1)
  6344.         order by name
  6345.  
  6346.     return (0)
  6347. end
  6348.  
  6349. /*
  6350. **  Check to see if group exists.
  6351. */
  6352. if not exists (select * from sysusers where name = @grpname
  6353.         and (issqlrole = 1))
  6354.     begin
  6355.         raiserror(15014,-1,-1,@grpname)
  6356.         return (1)
  6357.     end
  6358.  
  6359. /*
  6360. **  List the particulars for the group.
  6361. */
  6362. select Group_name = substring(g.name, 1, 25), Group_id = g.uid,
  6363.        Users_in_group = substring(u.name, 1, 25),
  6364.        Userid = u.uid
  6365.     from sysusers u, sysusers g, sysmembers m
  6366.     where g.name = @grpname
  6367.         and g.uid = m.groupuid
  6368.         and (g.issqlrole = 1)
  6369.         and u.uid = m.memberuid
  6370.     order by 1, 2
  6371.  
  6372. return (0) -- sp_helpgroup
  6373. go
  6374.  
  6375.  
  6376.  
  6377.  
  6378.  
  6379. raiserror(15339,-1,-1,'sp_helplog')
  6380. go
  6381. create procedure sp_helplog --- 1996/04/08 00:00
  6382. as
  6383. declare @firstpage int,
  6384.     @devname nvarchar(257),
  6385.     @msg nvarchar(255)
  6386.  
  6387. raiserror('sp_helplog is no longer supported.',1,1)
  6388.  
  6389. return (0) -- sp_helplog
  6390. go
  6391.  
  6392.  
  6393.  
  6394. raiserror(15339,-1,-1,'sp_helplogins')
  6395. go
  6396. CREATE PROCEDURE sp_helplogins  --- 1996/08/12 14:34
  6397.  
  6398.     @LoginNamePattern     sysname    = NULL
  6399. AS
  6400.  
  6401. Set nocount on
  6402.  
  6403. Declare
  6404.         @exec_stmt nvarchar(3550)
  6405.  
  6406. Declare
  6407.        @RetCode                        int
  6408.       ,@CountSkipPossUsers             int
  6409.       ,@Int1                           int
  6410.  
  6411. Declare
  6412.        @c10DBName                      sysname
  6413.       ,@c10DBStatus                    int
  6414.       ,@c10DBSID                       varbinary(85)
  6415.  
  6416. Declare
  6417.        @charMaxLenLoginName            varchar(11)
  6418.       ,@charMaxLenDBName               varchar(11)
  6419.       ,@charMaxLenUserName             varchar(11)
  6420.       ,@charMaxLenLangName             varchar(11)
  6421.  
  6422. Declare
  6423.        @DBOptLoading                   int   --0x0020      32  "DoNotRecover"
  6424.       ,@DBOptPreRecovery               int   --0x0040      64
  6425.       ,@DBOptRecovering                int   --0x0080     128
  6426.  
  6427.       ,@DBOptSuspect                   int   --0x0100     256  ("not recovered")
  6428.       ,@DBOptOffline                   int   --0x0200     512
  6429.       ,@DBOptDBOUseOnly                int   --0x0800    2048
  6430.  
  6431.       ,@DBOptSingleUser                int   --0x1000    4096
  6432.  
  6433.  
  6434. -------------  create work holding tables  ----------------
  6435. /*Create temp tables before any DML to ensure dynamic*/
  6436.  
  6437. CREATE Table #tb2_PlainLogins
  6438.    (
  6439.     LoginName                       sysname        collate database_default NOT Null
  6440.    ,SID                             varchar(85)    collate database_default NOT Null
  6441.    ,DefDBName                       sysname           collate database_default Null
  6442.    ,DefLangName                     sysname        collate database_default Null
  6443.    ,AUser                           char(5)        collate database_default Null
  6444.    ,ARemote                         char(7)        collate database_default Null
  6445.    )
  6446.  
  6447. CREATE Table #tb1_UA
  6448.    (
  6449.     LoginName                       sysname        collate database_default NOT Null
  6450.    ,DBName                          sysname        collate database_default NOT Null
  6451.    ,UserName                        sysname        collate database_default NOT Null
  6452.    ,UserOrAlias                     char(8)        collate database_default NOT Null
  6453.    )
  6454.  
  6455. ----------------  Initial data values  -------------------
  6456.  
  6457. Select
  6458.        @RetCode                        = 0  -- 0=good ,1=bad
  6459.       ,@CountSkipPossUsers             = 0
  6460.  
  6461.  
  6462. ----------------  Only SA can run this  -------------------
  6463.  
  6464.  
  6465. IF (not (is_srvrolemember('securityadmin') = 1))
  6466.    begin
  6467.    raiserror(15247,-1,-1)
  6468.    Select @RetCode = 1
  6469.    goto label_86return
  6470.    end
  6471.  
  6472. ----------------------  spt_values  ----------------
  6473. -------- 'D'
  6474.  
  6475. SELECT       @DBOptLoading       = number
  6476.       from   master.dbo.spt_values
  6477.       where  type                = 'D'
  6478.       and    name                = 'loading'
  6479.  
  6480. SELECT       @DBOptPreRecovery   = number
  6481.       from   master.dbo.spt_values
  6482.       where  type                = 'D'
  6483.       and    name                = 'pre recovery'
  6484.  
  6485. SELECT       @DBOptRecovering    = number
  6486.       from   master.dbo.spt_values
  6487.       where  type                = 'D'
  6488.       and    name                = 'recovering'
  6489.  
  6490. SELECT       @DBOptSuspect       = number
  6491.       from   master.dbo.spt_values
  6492.       where  type                = 'D'
  6493.       and    name                = 'not recovered'
  6494.  
  6495. SELECT       @DBOptOffline       = number
  6496.       from   master.dbo.spt_values
  6497.       where  type                = 'D'
  6498.       and    name                = 'offline'
  6499.  
  6500. SELECT       @DBOptDBOUseOnly    = number
  6501.       from   master.dbo.spt_values
  6502.       where  type                = 'D'
  6503.       and    name                = 'dbo use only'
  6504.  
  6505. SELECT       @DBOptSingleUser    = number
  6506.       from   master.dbo.spt_values
  6507.       where  type                = 'D'
  6508.       and    name                = 'single user'
  6509.  
  6510.  
  6511.  
  6512. ---------------  Cursor, for DBNames  -------------------
  6513.  
  6514.  
  6515. DECLARE ms_crs_10_DB
  6516.    Cursor local static For
  6517. SELECT
  6518.              name ,status ,sid
  6519.       from
  6520.              master.dbo.sysdatabases
  6521.  
  6522.  
  6523.  
  6524. OPEN ms_crs_10_DB
  6525.  
  6526.  
  6527. -----------------  LOOP 10:  thru Databases  ------------------
  6528.  
  6529.  
  6530. --------------
  6531. WHILE (10 = 10)
  6532.    begin    --LOOP 10: thru Databases
  6533.  
  6534.  
  6535.    FETCH
  6536.              Next
  6537.       from
  6538.              ms_crs_10_DB
  6539.       into
  6540.              @c10DBName
  6541.             ,@c10DBStatus
  6542.             ,@c10DBSID
  6543.  
  6544.  
  6545.    IF (@@fetch_status <> 0)
  6546.       begin
  6547.       Deallocate ms_crs_10_DB
  6548.       BREAK
  6549.       end
  6550.  
  6551.  
  6552. --------------------  Okay if we peek inside this DB now?
  6553.  
  6554.  
  6555.    IF (     @c10DBStatus & @DBOptDBOUseOnly  > 0
  6556.        AND  @c10DBSID                       <> suser_sid()
  6557.       )
  6558.       begin
  6559.       Select @CountSkipPossUsers = @CountSkipPossUsers + 1
  6560.       CONTINUE
  6561.       end
  6562.  
  6563.  
  6564.    IF (@c10DBStatus & @DBOptSingleUser  > 0)
  6565.       begin
  6566.  
  6567.       SELECT    @Int1 = count(*)
  6568.          from   master.dbo.sysprocesses
  6569.          where  spid <> @@spid
  6570.          and    dbid  = db_id(@c10DBName)
  6571.  
  6572.       IF (@Int1 > 0)
  6573.          begin
  6574.          Select @CountSkipPossUsers = @CountSkipPossUsers + 1
  6575.          CONTINUE
  6576.          end
  6577.       end
  6578.  
  6579.  
  6580.    IF (@c10DBStatus &
  6581.          (
  6582.            @DBOptLoading
  6583.          | @DBOptRecovering
  6584.          | @DBOptSuspect
  6585.          | @DBOptPreRecovery
  6586.          )
  6587.                > 0
  6588.       )
  6589.       begin
  6590.       Select @CountSkipPossUsers = @CountSkipPossUsers + 1
  6591.       CONTINUE
  6592.       end
  6593.  
  6594.  
  6595.    IF (@c10DBStatus &
  6596.          (
  6597.            @DBOptOffline
  6598.          )
  6599.                > 0
  6600.       )
  6601.       begin
  6602.       --Select @CountSkipPossUsers = @CountSkipPossUsers + 1
  6603.       CONTINUE
  6604.       end
  6605.  
  6606.     IF (has_dbaccess(@c10DBName) <> 1)
  6607.       begin
  6608.       raiserror(15622,-1,-1, @c10DBName)
  6609.       CONTINUE
  6610.       end
  6611.  
  6612.  
  6613.  
  6614. ---------------------  Add the User info to holding table.
  6615.     select @exec_stmt = '
  6616.    INSERT    #tb1_UA
  6617.             (
  6618.              DBName
  6619.             ,LoginName
  6620.             ,UserName
  6621.             ,UserOrAlias
  6622.             )
  6623.       Select
  6624.              N' + quotename(@c10DBName, '''') + '
  6625.             ,l.loginname
  6626.             ,u.name
  6627.             ,''User''
  6628.          from
  6629.              ' + quotename(@c10DBName, '[') + '.dbo.sysusers       u
  6630.             ,master.dbo.syslogins                  l
  6631.          where
  6632.              u.sid  = l.sid AND isaliased=0' +
  6633.             case @LoginNamePattern
  6634.             when null then ''
  6635.             else ' and ( l.name = N' + quotename(@LoginNamePattern , '''') + '
  6636.                 or l.loginname = N' + quotename(@LoginNamePattern , '''') + ')'
  6637.             end
  6638.             +
  6639. '     UNION
  6640.       Select
  6641.  
  6642.              N' + quotename(@c10DBName, '''') + '
  6643.             ,l.loginname
  6644.             ,u2.name
  6645.             ,''MemberOf''
  6646.          from
  6647.              ' + quotename(@c10DBName, '[')+ '.dbo.sysmembers       m
  6648.             ,' + quotename(@c10DBName, '[')+ '.dbo.sysusers       u1
  6649.             ,' + quotename(@c10DBName, '[')+ '.dbo.sysusers       u2
  6650.             ,master.dbo.syslogins                  l
  6651.          where
  6652.              u1.sid     = l.sid
  6653.          and m.memberuid = u1.uid
  6654.          and m.groupuid  = u2.uid' +
  6655.             case @LoginNamePattern
  6656.             when null then ''
  6657.             else ' and ( l.name = N' + quotename(@LoginNamePattern , '''') + '
  6658.                 or l.loginname = N' + quotename(@LoginNamePattern , '''') + ')'
  6659.             end
  6660.  
  6661.    EXECUTE(@exec_stmt)
  6662.  
  6663.    end --loop 10
  6664.  
  6665.  
  6666.  
  6667. ---------------  Populate plain logins work table  ---------------
  6668.  
  6669.  
  6670. INSERT       #tb2_PlainLogins
  6671.             (
  6672.              LoginName
  6673.             ,SID
  6674.             ,DefDBName
  6675.             ,DefLangName
  6676.             ,AUser
  6677.             ,ARemote
  6678.             )
  6679.    SELECT
  6680.              loginname
  6681.             ,convert(varchar(85), sid)
  6682.             ,dbname
  6683.             ,language
  6684.             ,Null
  6685.             ,Null
  6686.       from
  6687.              master.dbo.syslogins
  6688.       where
  6689.              @LoginNamePattern is null
  6690.              or name = @LoginNamePattern
  6691.              or loginname = @LoginNamePattern
  6692.  
  6693.  
  6694. -- AUser
  6695.  
  6696. UPDATE       #tb2_PlainLogins --(1996/08/12)
  6697.       set
  6698.              AUser  = 'yes'
  6699.       from
  6700.              #tb2_PlainLogins
  6701.             ,#tb1_UA             tb1
  6702.       where
  6703.              #tb2_PlainLogins.LoginName     = tb1.LoginName
  6704.       and    #tb2_PlainLogins.AUser        IS Null
  6705.  
  6706.  
  6707.  
  6708. UPDATE       #tb2_PlainLogins
  6709.       set
  6710.              AUser    =
  6711.                   CASE @CountSkipPossUsers
  6712.                      When  0  Then  'NO'
  6713.                      Else           '?'
  6714.                   END
  6715.       where
  6716.              AUser   IS Null
  6717.  
  6718.  
  6719. -- ARemote
  6720.  
  6721. UPDATE       #tb2_PlainLogins
  6722.       set
  6723.              ARemote   = 'YES'
  6724.       from
  6725.              #tb2_PlainLogins
  6726.             ,master.dbo.sysremotelogins   rl
  6727.       where
  6728.              #tb2_PlainLogins.SID = rl.sid
  6729.       and    #tb2_PlainLogins.ARemote                 IS Null
  6730.  
  6731.  
  6732.  
  6733. UPDATE       #tb2_PlainLogins
  6734.       set
  6735.              ARemote  = 'no'
  6736.       where
  6737.              ARemote IS Null
  6738.  
  6739.  
  6740.  
  6741. ------------  Optimize widths for plain Logins report  ----------
  6742.  
  6743.  
  6744. SELECT
  6745.              @charMaxLenLoginName      =
  6746.                   convert ( varchar
  6747.                            ,isnull ( max(datalength(LoginName)) ,9)
  6748.                           )
  6749.             ,@charMaxLenDBName         =
  6750.                   convert ( varchar
  6751.                            , isnull (max(isnull (datalength(DefDBName) ,9)) ,9)
  6752.                           )
  6753.             ,@charMaxLenLangName   =
  6754.                   convert ( varchar
  6755.                            , isnull (max(isnull (datalength(DefLangName) ,11)) ,11)
  6756.                           )
  6757.       from
  6758.              #tb2_PlainLogins
  6759.  
  6760.  
  6761.  
  6762. ----------------  Print out plain Logins report  -------------
  6763.  
  6764. /*** Message Handlers get confused.
  6765. Raiserror('...Logins...' ,0,1)
  6766. ***/
  6767.  
  6768. EXECUTE(
  6769. '
  6770. Set nocount off
  6771.  
  6772.  
  6773. SELECT
  6774.           ''LoginName''       = substring (LoginName     ,1 ,'
  6775.                                        + @charMaxLenLoginName   + ')
  6776.  
  6777.          ,''SID''             = convert(varbinary(85), SID)
  6778.  
  6779.          ,''DefDBName''       = substring (DefDBName     ,1 ,'
  6780.                                        + @charMaxLenDBName      + ')
  6781.  
  6782.          ,''DefLangName''     = substring (DefLangName   ,1 ,'
  6783.                                        + @charMaxLenLangName    + ')
  6784.  
  6785.          ,AUser
  6786.          ,ARemote
  6787.    from
  6788.           #tb2_PlainLogins
  6789.    order by
  6790.           LoginName
  6791.  
  6792.  
  6793. Set nocount on
  6794. '
  6795. )
  6796.  
  6797.  
  6798.  
  6799. ------------  Optimize UA report column display widths  -----------
  6800.  
  6801.  
  6802. SELECT
  6803.              @charMaxLenLoginName   =
  6804.                   convert ( varchar
  6805.                            ,isnull ( max(datalength(LoginName)) ,9)
  6806.                           )
  6807.             ,@charMaxLenDBName      =
  6808.                   convert ( varchar
  6809.                            ,isnull ( max(datalength(DBName)) ,6)
  6810.                           )
  6811.             ,@charMaxLenUserName    =
  6812.                   convert ( varchar
  6813.                            ,isnull ( max(datalength(UserName)) ,8)
  6814.                           )
  6815.       from
  6816.              #tb1_UA
  6817.  
  6818.  
  6819.  
  6820. ------------  Print out the UserOrAlias report  ------------
  6821.  
  6822. /***
  6823. Raiserror('...Logins-to-Users...' ,0,1)
  6824. ***/
  6825.  
  6826. EXECUTE(
  6827. '
  6828. Set nocount off
  6829.  
  6830.  
  6831. SELECT
  6832.           ''LoginName''    = substring (LoginName  ,1 ,'
  6833.                                        + @charMaxLenLoginName  + ')
  6834.  
  6835.          ,''DBName''       = substring (DBName     ,1 ,'
  6836.                                        + @charMaxLenDBName     + ')
  6837.  
  6838.          ,''UserName''     = substring (UserName   ,1 ,'
  6839.                                        + @charMaxLenUserName   + ')
  6840.  
  6841.          ,UserOrAlias
  6842.    from
  6843.           #tb1_UA
  6844.    order by
  6845.           1 ,2 ,3
  6846.  
  6847.  
  6848. Set nocount on
  6849. '
  6850. )
  6851.  
  6852.  
  6853. -----------------------  Finalization  --------------------
  6854. label_86return:
  6855.  
  6856. IF (object_id('#tb2_PlainLogins') IS NOT Null)
  6857.             DROP Table #tb2_PlainLogins
  6858.  
  6859. IF (object_id('#tb1_UA') IS NOT Null)
  6860.             DROP Table #tb1_UA
  6861.  
  6862. Return @RetCode -- sp_helplogins
  6863. go
  6864.  
  6865.  
  6866. raiserror(15339,-1,-1,'sp_helpindex')
  6867. go
  6868. create proc sp_helpindex
  6869.     @objname nvarchar(776)        -- the table to check for indexes
  6870. as
  6871.     -- PRELIM
  6872.     set nocount on
  6873.  
  6874.     declare @objid int,            -- the object id of the table
  6875.             @indid smallint,    -- the index id of an index
  6876.             @groupid smallint,  -- the filegroup id of an index
  6877.             @indname sysname,
  6878.             @groupname sysname,
  6879.             @status int,
  6880.             @keys nvarchar(2126),    --Length (16*max_identifierLength)+(15*2)+(16*3)
  6881.             @dbname    sysname
  6882.  
  6883.     -- Check to see that the object names are local to the current database.
  6884.     select @dbname = parsename(@objname,3)
  6885.  
  6886.     if @dbname is not null and @dbname <> db_name()
  6887.     begin
  6888.             raiserror(15250,-1,-1)
  6889.             return (1)
  6890.     end
  6891.  
  6892.     -- Check to see the the table exists and initialize @objid.
  6893.     select @objid = object_id(@objname)
  6894.     if @objid is NULL
  6895.     begin
  6896.         select @dbname=db_name()
  6897.         raiserror(15009,-1,-1,@objname,@dbname)
  6898.         return (1)
  6899.     end
  6900.  
  6901.     -- OPEN CURSOR OVER INDEXES (skip stats: bug shiloh_51196)
  6902.     declare ms_crs_ind cursor local static for
  6903.         select indid, groupid, name, status from sysindexes
  6904.             where id = @objid and indid > 0 and indid < 255 and (status & 64)=0 order by indid
  6905.     open ms_crs_ind
  6906.     fetch ms_crs_ind into @indid, @groupid, @indname, @status
  6907.  
  6908.     -- IF NO INDEX, QUIT
  6909.     if @@fetch_status < 0
  6910.     begin
  6911.         deallocate ms_crs_ind
  6912.         raiserror(15472,-1,-1) --'Object does not have any indexes.'
  6913.         return (0)
  6914.     end
  6915.  
  6916.     -- create temp table
  6917.     create table #spindtab
  6918.     (
  6919.         index_name            sysname    collate database_default NOT NULL,
  6920.         stats                int,
  6921.         groupname            sysname collate database_default NULL,
  6922.         index_keys            nvarchar(2126)    collate database_default NOT NULL -- see @keys above for length descr
  6923.     )
  6924.  
  6925.     -- Now check out each index, figure out its type and keys and
  6926.     --    save the info in a temporary table that we'll print out at the end.
  6927.     while @@fetch_status >= 0
  6928.     begin
  6929.         -- First we'll figure out what the keys are.
  6930.         declare @i int, @thiskey nvarchar(131) -- 128+3
  6931.  
  6932.         select @keys = index_col(@objname, @indid, 1), @i = 2
  6933.         if (indexkey_property(@objid, @indid, 1, 'isdescending') = 1)
  6934.             select @keys = @keys  + '(-)'
  6935.  
  6936.         select @thiskey = index_col(@objname, @indid, @i)
  6937.         if ((@thiskey is not null) and (indexkey_property(@objid, @indid, @i, 'isdescending') = 1))
  6938.             select @thiskey = @thiskey + '(-)'
  6939.  
  6940.         while (@thiskey is not null )
  6941.         begin
  6942.             select @keys = @keys + ', ' + @thiskey, @i = @i + 1
  6943.             select @thiskey = index_col(@objname, @indid, @i)
  6944.             if ((@thiskey is not null) and (indexkey_property(@objid, @indid, @i, 'isdescending') = 1))
  6945.                 select @thiskey = @thiskey + '(-)'
  6946.         end
  6947.  
  6948.         select @groupname = null
  6949.         select @groupname = groupname from sysfilegroups where groupid = @groupid
  6950.  
  6951.         -- INSERT ROW FOR INDEX
  6952.         insert into #spindtab values (@indname, @status, @groupname, @keys)
  6953.  
  6954.         -- Next index
  6955.         fetch ms_crs_ind into @indid, @groupid, @indname, @status
  6956.     end
  6957.     deallocate ms_crs_ind
  6958.  
  6959.     -- SET UP SOME CONSTANT VALUES FOR OUTPUT QUERY
  6960.     declare @empty varchar(1) select @empty = ''
  6961.     declare @des1            varchar(35),    -- 35 matches spt_values
  6962.             @des2            varchar(35),
  6963.             @des4            varchar(35),
  6964.             @des32            varchar(35),
  6965.             @des64            varchar(35),
  6966.             @des2048        varchar(35),
  6967.             @des4096        varchar(35),
  6968.             @des8388608        varchar(35),
  6969.             @des16777216    varchar(35)
  6970.     select @des1 = name from master.dbo.spt_values where type = 'I' and number = 1
  6971.     select @des2 = name from master.dbo.spt_values where type = 'I' and number = 2
  6972.     select @des4 = name from master.dbo.spt_values where type = 'I' and number = 4
  6973.     select @des32 = name from master.dbo.spt_values where type = 'I' and number = 32
  6974.     select @des64 = name from master.dbo.spt_values where type = 'I' and number = 64
  6975.     select @des2048 = name from master.dbo.spt_values where type = 'I' and number = 2048
  6976.     select @des4096 = name from master.dbo.spt_values where type = 'I' and number = 4096
  6977.     select @des8388608 = name from master.dbo.spt_values where type = 'I' and number = 8388608
  6978.     select @des16777216 = name from master.dbo.spt_values where type = 'I' and number = 16777216
  6979.  
  6980.     -- DISPLAY THE RESULTS
  6981.     select
  6982.         'index_name' = index_name,
  6983.         'index_description' = convert(varchar(210), --bits 16 off, 1, 2, 16777216 on, located on group
  6984.                 case when (stats & 16)<>0 then 'clustered' else 'nonclustered' end
  6985.                 + case when (stats & 1)<>0 then ', '+@des1 else @empty end
  6986.                 + case when (stats & 2)<>0 then ', '+@des2 else @empty end
  6987.                 + case when (stats & 4)<>0 then ', '+@des4 else @empty end
  6988.                 + case when (stats & 64)<>0 then ', '+@des64 else case when (stats & 32)<>0 then ', '+@des32 else @empty end end
  6989.                 + case when (stats & 2048)<>0 then ', '+@des2048 else @empty end
  6990.                 + case when (stats & 4096)<>0 then ', '+@des4096 else @empty end
  6991.                 + case when (stats & 8388608)<>0 then ', '+@des8388608 else @empty end
  6992.                 + case when (stats & 16777216)<>0 then ', '+@des16777216 else @empty end
  6993.                 + ' located on ' + groupname),
  6994.         'index_keys' = index_keys
  6995.     from #spindtab
  6996.     order by index_name
  6997.  
  6998.  
  6999.     return (0) -- sp_helpindex
  7000. go
  7001.  
  7002. raiserror(15339,-1,-1,'sp_helpstats')
  7003. go
  7004.  
  7005. create proc sp_helpstats
  7006.     @objname nvarchar(520),        -- the table to check for statistics (to accomodate for 2 part names)
  7007.     @results nvarchar(5) = 'STATS'    -- 'ALL' returns indexes & stats, 'STATS' returns just stats
  7008. as
  7009.     -- PRELIM
  7010.     set nocount on
  7011.     declare     @objid int,            -- the object id of the table
  7012.             @indid smallint,    -- the index id of an index
  7013.             @indname sysname,
  7014.             @keys nvarchar(2078),-- string build index key list, length = (16*max_id_length)+(15*2)
  7015.             @dbname    sysname,
  7016.             @i int,
  7017.             @thiskey sysname,
  7018.             @curs    cursor
  7019.     -- Check to see the the table exists and initialize @objid.
  7020.     select @objid = object_id(@objname, 'local')
  7021.     if @objid is NULL
  7022.         begin
  7023.         select @dbname=db_name()
  7024.         raiserror(15009,-1,-1,@objname,@dbname)
  7025.         return (1)
  7026.         end
  7027.     If UPPER(@results) <> 'STATS' and UPPER(@results)<> 'ALL'
  7028.     BEGIN
  7029.             raiserror(N'Invalid option: %s', 1, 1, @results)
  7030.         return (1)
  7031.     END
  7032.  
  7033.     If UPPER(@results) = 'STATS'
  7034.     BEGIN
  7035.         set @curs = cursor local fast_forward READ_ONLY for
  7036.             select indid, name from sysindexes
  7037.             where id = @objid and indid > 0 and indid < 255
  7038.               and (status & (64 | 8388608)) > 0 order by indid -- User created & auto-created stats
  7039.     END
  7040.     ELSE
  7041.     BEGIN
  7042.         set @curs = cursor local fast_forward READ_ONLY for
  7043.             select indid, name from sysindexes
  7044.             where id = @objid and indid > 0 and indid < 255
  7045.               order by indid -- Indexes, User created & auto-created stats
  7046.     END
  7047.  
  7048.     open @curs
  7049.     fetch @curs into @indid, @indname
  7050.  
  7051.     -- IF NO STATISTICS, QUIT
  7052.     if @@fetch_status < 0
  7053.     begin
  7054.         deallocate @curs
  7055.         If UPPER(@results) = 'STATS'
  7056.         BEGIN
  7057.             raiserror(15574,-1,-1) --'Object does not have any statistics.'
  7058.         END
  7059.         ELSE
  7060.         BEGIN
  7061.             raiserror(15575,-1,-1) --'Object does not have any indexes or statistics.'
  7062.         END
  7063.     return (0)
  7064.     end
  7065.     -- create temp table
  7066.     create table #spstattab
  7067.     (
  7068.         stats_name            sysname    collate database_default NOT NULL,
  7069.         stats_keys            nvarchar(2078)    collate database_default NOT NULL
  7070.     )
  7071.  
  7072.     -- Now check out each statistics set, figure out its keys and
  7073.     --    save the info in a temporary table that we'll print out at the end.
  7074.     while @@fetch_status >= 0
  7075.     begin
  7076.         -- First we'll figure out what the keys are.
  7077.  
  7078.         select @keys = index_col(@objname, @indid, 1),
  7079.                 @i = 2, @thiskey = index_col(@objname, @indid, 2)
  7080.         while (@thiskey is not null )
  7081.         begin
  7082.             select @keys = @keys + ', ' + @thiskey, @i = @i + 1
  7083.             select @thiskey = index_col(@objname, @indid, @i)
  7084.         end
  7085.  
  7086.         -- INSERT ROW FOR INDEX
  7087.         insert into #spstattab values (@indname, @keys)
  7088.  
  7089.         -- Next index
  7090.         fetch @curs into @indid, @indname
  7091.     end
  7092.     deallocate @curs
  7093.  
  7094.     -- DISPLAY THE RESULTS
  7095.     select
  7096.         'statistics_name' = stats_name,
  7097.         'statistics_keys' = stats_keys
  7098.     from #spstattab
  7099.     order by stats_name
  7100.  
  7101. return (0) -- sp_helpstats
  7102.  
  7103. raiserror(15339,-1,-1,'sp_objectfilegroup')
  7104. go
  7105. create procedure sp_objectfilegroup --- 1996/08/30 17:44
  7106. @objid    int
  7107. as
  7108.     /*
  7109.     ** Print out the object's data filegroup if applicable.
  7110.     */
  7111.     if exists (select * from sysobjects
  7112.             where id = @objid
  7113.             and type in ('S ','U '))
  7114.         begin
  7115.             select Data_located_on_filegroup = s.groupname
  7116.             from sysfilegroups s, sysindexes i
  7117.             where i.id = @objid
  7118.                 and i.indid < 2
  7119.                 and i.groupid = s.groupid
  7120.         end
  7121.  
  7122.     /*
  7123.     **  It's not a table so segment is not applicable.
  7124.     */
  7125.     else
  7126.         select Data_located_on_filegroup = 'not applicable'
  7127.  
  7128. return (0) -- sp_objectfilegroup
  7129. go
  7130.  
  7131. raiserror(15339,-1,-1,'sp_help')
  7132. go
  7133. create proc sp_help
  7134.     @objname nvarchar(776) = NULL        -- object name we're after
  7135. as
  7136.     -- PRELIMINARY
  7137.     set nocount on
  7138.     declare    @dbname    sysname
  7139.  
  7140.     -- OBTAIN DISPLAY STRINGS FROM spt_values UP FRONT --
  7141.     declare @no varchar(35), @yes varchar(35), @none varchar(35)
  7142.     select @no = name from master.dbo.spt_values where type = 'B' and number = 0
  7143.     select @yes = name from master.dbo.spt_values where type = 'B' and number = 1
  7144.     select @none = name from master.dbo.spt_values where type = 'B' and number = 2
  7145.  
  7146.     -- If no @objname given, give a little info about all objects.
  7147.     if @objname is null
  7148.     begin
  7149.         -- DISPLAY ALL SYSOBJECTS --
  7150.         select
  7151.             'Name'          = o.name,
  7152.             'Owner'         = user_name(uid),
  7153.             'Object_type'   = substring(v.name,5,31)
  7154.         from sysobjects o, master.dbo.spt_values v
  7155.         where o.xtype = substring(v.name,1,2) collate database_default and v.type = 'O9T'
  7156.         order by Object_type desc, Name asc
  7157.  
  7158.         print ' '
  7159.  
  7160.         -- DISPLAY ALL USER TYPES
  7161.         select
  7162.             'User_type'        = name,
  7163.             'Storage_type'    = type_name(xtype),
  7164.             'Length'        = length,
  7165.             'Prec'            = TypeProperty(name, 'precision'),
  7166.             'Scale'            = TypeProperty(name, 'scale'),
  7167.             'Nullable'        = case when TypeProperty(name, 'AllowsNull') = 1
  7168.                                             then @yes else @no end,
  7169.             'Default_name'    = isnull(object_name(tdefault), @none),
  7170.             'Rule_name'        = isnull(object_name(domain), @none),
  7171.             'Collation'        = collation
  7172.         from systypes
  7173.         where xusertype > 256
  7174.         order by name
  7175.  
  7176.         return(0)
  7177.     end
  7178.  
  7179.     -- Make sure the @objname is local to the current database.
  7180.     select @dbname = parsename(@objname,3)
  7181.  
  7182.     if @dbname is not null and @dbname <> db_name()
  7183.         begin
  7184.             raiserror(15250,-1,-1)
  7185.             return(1)
  7186.         end
  7187.  
  7188.     -- @objname must be either sysobjects or systypes: first look in sysobjects
  7189.     declare @objid int
  7190.     declare @sysobj_type char(2)
  7191.     select @objid = id, @sysobj_type = xtype from sysobjects where id = object_id(@objname)
  7192.  
  7193.     -- IF NOT IN SYSOBJECTS, TRY SYSTYPES --
  7194.     if @objid is null
  7195.     begin
  7196.         -- UNDONE: SHOULD CHECK FOR AND DISALLOW MULTI-PART NAME
  7197.         select @objid = xusertype from systypes where name = @objname
  7198.  
  7199.         -- IF NOT IN SYSTYPES, GIVE UP
  7200.         if @objid is null
  7201.         begin
  7202.             select @dbname=db_name()
  7203.             raiserror(15009,-1,-1,@objname,@dbname)
  7204.             return(1)
  7205.         end
  7206.  
  7207.         -- DATA TYPE HELP (prec/scale only valid for numerics)
  7208.         select
  7209.             'Type_name'        = name,
  7210.             'Storage_type'    = type_name(xtype),
  7211.             'Length'        = length,
  7212.             'Prec'            = TypeProperty(name, 'precision'),
  7213.             'Scale'            = TypeProperty(name, 'scale'),
  7214.             'Nullable'        = case when allownulls=1 then @yes else @no end,
  7215.             'Default_name'    = isnull(object_name(tdefault), @none),
  7216.             'Rule_name'        = isnull(object_name(domain), @none),
  7217.             'Collation'        = collation
  7218.         from systypes
  7219.         where xusertype = @objid
  7220.  
  7221.         return(0)
  7222.     end
  7223.  
  7224.     -- FOUND IT IN SYSOBJECT, SO GIVE OBJECT INFO
  7225.     select
  7226.         'Name'                = o.name,
  7227.         'Owner'                = user_name(uid),
  7228.         'Type'              = substring(v.name,5,31),
  7229.         'Created_datetime'    = o.crdate
  7230.     from sysobjects o, master.dbo.spt_values v
  7231.     where o.id = @objid and o.xtype = substring(v.name,1,2) collate database_default and v.type = 'O9T'
  7232.  
  7233.     print ' '
  7234.  
  7235.     -- DISPLAY COLUMN IF TABLE / VIEW
  7236.     if @sysobj_type in ('S ','U ','V ','TF','IF')
  7237.     begin
  7238.  
  7239.         -- SET UP NUMERIC TYPES: THESE WILL HAVE NON-BLANK PREC/SCALE
  7240.         declare @numtypes nvarchar(80)
  7241.         select @numtypes = N'tinyint,smallint,decimal,int,real,money,float,numeric,smallmoney'
  7242.  
  7243.         -- INFO FOR EACH COLUMN
  7244.         print ' '
  7245.         select
  7246.             'Column_name'            = name,
  7247.             'Type'                    = type_name(xusertype),
  7248.             'Computed'                = case when iscomputed = 0 then @no else @yes end,
  7249.             'Length'                = convert(int, length),
  7250.             'Prec'                    = case when charindex(type_name(xtype), @numtypes) > 0
  7251.                                         then convert(char(5),ColumnProperty(id, name, 'precision'))
  7252.                                         else '     ' end,
  7253.             'Scale'                    = case when charindex(type_name(xtype), @numtypes) > 0
  7254.                                         then convert(char(5),OdbcScale(xtype,xscale))
  7255.                                         else '     ' end,
  7256.             'Nullable'                = case when isnullable = 0 then @no else @yes end,
  7257.             'TrimTrailingBlanks'    = case ColumnProperty(@objid, name, 'UsesAnsiTrim')
  7258.                                         when 1 then @no
  7259.                                         when 0 then @yes
  7260.                                         else '(n/a)' end,
  7261.             'FixedLenNullInSource'    = case
  7262.                         when type_name(xtype) not in ('varbinary','varchar','binary','char')
  7263.                             Then '(n/a)'
  7264.                         When status & 0x20 = 0 Then @no
  7265.                         Else @yes END,
  7266.             'Collation'        = collation
  7267.         from syscolumns where id = @objid and number = 0 order by colid
  7268.  
  7269.         -- IDENTITY COLUMN?
  7270.         if @sysobj_type in ('S ','U ','V ','TF')
  7271.         begin
  7272.             print ' '
  7273.             declare @colname sysname
  7274.             select @colname = name from syscolumns where id = @objid
  7275.                         and colstat & 1 = 1
  7276.             select
  7277.                 'Identity'                = isnull(@colname,'No identity column defined.'),
  7278.                 'Seed'                    = ident_seed(@objname),
  7279.                 'Increment'                = ident_incr(@objname),
  7280.                 'Not For Replication'    = ColumnProperty(@objid, @colname, 'IsIDNotForRepl')
  7281.             -- ROWGUIDCOL?
  7282.             print ' '
  7283.             select @colname = null
  7284.             select @colname = name from syscolumns where id = @objid and number = 0
  7285.                         and ColumnProperty(@objid, name, 'IsRowGuidCol') = 1
  7286.             select 'RowGuidCol' = isnull(@colname,'No rowguidcol column defined.')
  7287.         end
  7288.     end
  7289.  
  7290.     -- DISPLAY PROC PARAMS
  7291.     if @sysobj_type in ('P ') --RF too?
  7292.     begin
  7293.         -- ANY PARAMS FOR THIS PROC?
  7294.         if exists (select id from syscolumns where id = @objid)
  7295.         begin
  7296.             -- INFO ON PROC PARAMS
  7297.             print ' '
  7298.             select
  7299.                 'Parameter_name'    = name,
  7300.                 'Type'                = type_name(xusertype),
  7301.                 'Length'            = length,
  7302.                 'Prec'                = case when type_name(xtype) = 'uniqueidentifier' then xprec
  7303.                                         else OdbcPrec(xtype, length, xprec) end,
  7304.                 'Scale'                = OdbcScale(xtype,xscale),
  7305.                 'Param_order'        = colid,
  7306.                 'Collation'        = collation
  7307.  
  7308.             from syscolumns where id = @objid
  7309.         end
  7310.     end
  7311.  
  7312.     -- DISPLAY TABLE INDEXES & CONSTRAINTS
  7313.     if @sysobj_type in ('S ','U ')
  7314.     begin
  7315.         print ' '
  7316.         execute sp_objectfilegroup @objid
  7317.         print ' '
  7318.         execute sp_helpindex @objname
  7319.         print ' '
  7320.         execute sp_helpconstraint @objname,'nomsg'
  7321.         if (select count(*) from sysdepends where depid = @objid and deptype = 1) = 0
  7322.         begin
  7323.             raiserror(15647,-1,-1) -- 'No views with schemabinding reference this table.'
  7324.         end
  7325.         else
  7326.         begin
  7327.             select distinct 'Table is referenced by views' = obj.name from sysobjects obj, sysdepends deps
  7328.                 where obj.xtype ='V' and obj.id = deps.id and deps.depid = @objid
  7329.                     and deps.deptype = 1 group by obj.name
  7330.  
  7331.         end
  7332.     end
  7333.     else if @sysobj_type in ('V ')
  7334.     begin
  7335.         -- VIEWS DONT HAVE CONSTRAINTS, BUT PRINT THESE MESSAGES BECAUSE 6.5 DID
  7336.         print ' '
  7337.         raiserror(15469,-1,-1) -- No constraints defined
  7338.         print ' '
  7339.         raiserror(15470,-1,-1) --'No foreign keys reference this table.'
  7340.         execute sp_helpindex @objname
  7341.     end
  7342.  
  7343.     return (0) -- sp_help
  7344. go
  7345.  
  7346. checkpoint
  7347. go
  7348.  
  7349.  
  7350. raiserror(15339,-1,-1,'sp_helprotect')
  7351. go
  7352. CREATE PROCEDURE sp_helprotect
  7353.     @name                ncharacter varying(776)  = NULL
  7354.     ,@username            sysname  = NULL
  7355.     ,@grantorname        sysname  = NULL
  7356.     ,@permissionarea    character varying(10)  = 'o s'
  7357. as
  7358.  
  7359. /********
  7360. Explanation of the parms...
  7361. ---------------------------
  7362. @name:  Name of [Owner.]Object and Statement; meaning
  7363. for sysprotects.id and sysprotects.action at the
  7364. same time; thus see parm @permissionarea.
  7365.    Examples-   'user2.tb'  , 'CREATE TABLE', null
  7366.  
  7367. @username:  Name of the grantee (for sysprotects.uid).
  7368.    Examples-   'user2', null
  7369.  
  7370. @grantorname:  Name of the grantor (for sysprotects.grantor).
  7371.    Examples-   'user2' --Would prevent report rows which would
  7372.                        --  have 'dbo' as grantor.
  7373.  
  7374. @permissionarea:  O=Object, S=Statement; include all which apply.
  7375.    Examples-   'o'  , ',s'  , 'os'  , 'so'  , 's o'  , 's,o'
  7376. GeneMi
  7377. ********/
  7378.  
  7379.     Set nocount on
  7380.  
  7381.     Declare
  7382.     @vc1                   sysname
  7383.     ,@Int1                  integer
  7384.  
  7385.     Declare
  7386.     @charMaxLenOwner        character varying(11)
  7387.     ,@charMaxLenObject        character varying(11)
  7388.     ,@charMaxLenGrantee        character varying(11)
  7389.     ,@charMaxLenGrantor        character varying(11)
  7390.     ,@charMaxLenAction        character varying(11)
  7391.     ,@charMaxLenColumnName    character varying(11)
  7392.  
  7393.     Declare
  7394.     @OwnerName                sysname
  7395.     ,@ObjectStatementName    sysname
  7396.  
  7397.  
  7398.     /* Perform temp table DDL here to minimize compilation costs*/
  7399. CREATE Table #t1_Prots
  7400.     (    Id                    int                Null
  7401.         ,Type1Code            char(6)            collate database_default NOT Null
  7402.         ,ObjType            char(2)            collate database_default Null
  7403.  
  7404.         ,ActionName        varchar(20)            collate database_default Null
  7405.         ,ActionCategory    char(2)                collate database_default Null
  7406.         ,ProtectTypeName    char(10)        collate database_default Null
  7407.  
  7408.         ,Columns_Orig        varbinary(32)    Null
  7409.  
  7410.         ,OwnerName            sysname            collate database_default NOT Null
  7411.         ,ObjectName            sysname            collate database_default NOT Null
  7412.         ,GranteeName        sysname            collate database_default NOT Null
  7413.         ,GrantorName        sysname            collate database_default NOT Null
  7414.  
  7415.         ,ColumnName            sysname            collate database_default Null
  7416.         ,ColId                smallint        Null
  7417.  
  7418.         ,Max_ColId            smallint        Null
  7419.         ,All_Col_Bits_On    tinyint            Null
  7420.         ,new_Bit_On            tinyint            Null )  -- 1=yes on
  7421.  
  7422.  
  7423.     /*    Check for valid @permissionarea */
  7424.     Select @permissionarea = upper( isnull(@permissionarea,'?') )
  7425.  
  7426.     IF (    charindex('O',@permissionarea) <= 0
  7427.         AND  charindex('S',@permissionarea) <= 0)
  7428.     begin
  7429.         raiserror(15300,-1,-1 ,@permissionarea,'o,s')
  7430.         return (1)
  7431.     end
  7432.  
  7433.     select @vc1 = parsename(@name,3)
  7434.  
  7435.     /* Verified db qualifier is current db*/
  7436.     IF (@vc1 is not null and @vc1 <> db_name())
  7437.     begin
  7438.         raiserror(15302,-1,-1)  --Do not qualify with DB name.
  7439.         return (1)
  7440.     end
  7441.  
  7442.     /*  Derive OwnerName and @ObjectStatementName*/
  7443.     select    @OwnerName                =    parsename(@name, 2)
  7444.             ,@ObjectStatementName    =    parsename(@name, 1)
  7445.  
  7446.     IF (@ObjectStatementName is NULL and @name is not null)
  7447.     begin
  7448.         raiserror(15253,-1,-1,@name)
  7449.         return (1)
  7450.     end
  7451.  
  7452.     /*    Copy info from sysprotects for processing    */
  7453.     IF charindex('O',@permissionarea) > 0
  7454.     begin
  7455.         /*    Copy info for objects    */
  7456.         INSERT    #t1_Prots
  7457.         (    Id
  7458.             ,Type1Code
  7459.  
  7460.             ,ObjType
  7461.             ,ActionName
  7462.             ,ActionCategory
  7463.             ,ProtectTypeName
  7464.  
  7465.             ,Columns_Orig
  7466.             ,OwnerName
  7467.             ,ObjectName
  7468.             ,GranteeName
  7469.  
  7470.             ,GrantorName
  7471.             ,ColumnName
  7472.             ,ColId
  7473.  
  7474.             ,Max_ColId
  7475.             ,All_Col_Bits_On
  7476.             ,new_Bit_On    )
  7477.  
  7478.     /*    1Regul indicates action can be at column level,
  7479.         2Simpl indicates action is at the object level */
  7480.         SELECT    id
  7481.                 ,case
  7482.                     when columns is null then '2Simpl'
  7483.                     else '1Regul'
  7484.                 end
  7485.  
  7486.                 ,Null
  7487.                 ,val1.name
  7488.                 ,'Ob'
  7489.                 ,val2.name
  7490.  
  7491.                 ,columns
  7492.                 ,user_name(objectproperty( id, 'ownerid' ))
  7493.                 ,object_name(id)
  7494.                 ,user_name(uid)
  7495.  
  7496.                 ,user_name(grantor)
  7497.                 ,case
  7498.                     when columns is null then '.'
  7499.                     else Null
  7500.                 end
  7501.                 ,-123
  7502.  
  7503.                 ,Null
  7504.                 ,Null
  7505.                 ,Null
  7506.         FROM    sysprotects sysp
  7507.                 ,master.dbo.spt_values  val1
  7508.                 ,master.dbo.spt_values  val2
  7509.         where    (@OwnerName is null or user_name(objectproperty( id, 'ownerid' )) = @OwnerName)
  7510.         and    (@ObjectStatementName is null or object_name(id) =  @ObjectStatementName)
  7511.         and    (@username is null or user_name(uid) =  @username)
  7512.         and    (@grantorname is null or user_name(grantor) =  @grantorname)
  7513.         and    val1.type     = 'T'
  7514.         and    val1.number   = sysp.action
  7515.         and    val2.type     = 'T' --T is overloaded.
  7516.         and    val2.number   = sysp.protecttype
  7517.         and sysp.id != 0
  7518.  
  7519.  
  7520.         IF EXISTS (SELECT * From #t1_Prots)
  7521.         begin
  7522.             UPDATE    #t1_Prots set ObjType = ob.xtype
  7523.             FROM    sysobjects    ob
  7524.             WHERE    ob.id    =  #t1_Prots.Id
  7525.  
  7526.  
  7527.             UPDATE     #t1_Prots
  7528.             set        Max_ColId = (select max(colid) from syscolumns sysc
  7529.                                 where #t1_Prots.Id = sysc.id)    -- colid may not consecutive if column dropped
  7530.             where Type1Code = '1Regul'
  7531.  
  7532.  
  7533.             /*    First bit set indicates actions pretains to new columns. (i.e. table-level permission)
  7534.                 Set new_Bit_On accordinglly                            */
  7535.             UPDATE    #t1_Prots SET new_Bit_On =
  7536.             CASE    convert(int,substring(Columns_Orig,1,1)) & 1
  7537.                 WHEN    1 then    1
  7538.                 ELSE    0
  7539.             END
  7540.             WHERE    ObjType    <> 'V'    and     Type1Code = '1Regul'
  7541.  
  7542.  
  7543.             /* Views don't get new columns    */
  7544.             UPDATE #t1_Prots set new_Bit_On = 0
  7545.             WHERE  ObjType = 'V'
  7546.  
  7547.  
  7548.             /*    Indicate enties where column level action pretains to all
  7549.                 columns in table All_Col_Bits_On = 1                    */
  7550.             UPDATE    #t1_Prots    set        All_Col_Bits_On = 1
  7551.             where    #t1_Prots.Type1Code     =  '1Regul'
  7552.             and    not exists 
  7553.                 (select *
  7554.                 from syscolumns sysc, master..spt_values v
  7555.                 where #t1_Prots.Id = sysc.id and sysc.colid = v.number
  7556.                 and v.number <= Max_ColId        -- column may be dropped/added after Max_ColId snap-shot 
  7557.                 and v.type = 'P' and
  7558.             /*    Columns_Orig where first byte is 1 means off means on and on mean off
  7559.                 where first byte is 0 means off means off and on mean on    */
  7560.                     case convert(int,substring(#t1_Prots.Columns_Orig, 1, 1)) & 1
  7561.                         when 0 then convert(tinyint, substring(#t1_Prots.Columns_Orig, v.low, 1))
  7562.                         else (~convert(tinyint, isnull(substring(#t1_Prots.Columns_Orig, v.low, 1),0)))
  7563.                     end & v.high = 0)
  7564.  
  7565.  
  7566.             /* Indicate entries where column level action pretains to
  7567.                 only some of columns in table  All_Col_Bits_On  =  0*/
  7568.             UPDATE    #t1_Prots    set  All_Col_Bits_On  =  0
  7569.             WHERE    #t1_Prots.Type1Code  =  '1Regul'
  7570.             and    All_Col_Bits_On  is  null
  7571.  
  7572.  
  7573.             Update #t1_Prots
  7574.             set ColumnName  =
  7575.             case
  7576.                 when All_Col_Bits_On = 1 and new_Bit_On = 1 then '(All+New)'
  7577.                 when All_Col_Bits_On = 1 and new_Bit_On = 0 then '(All)'
  7578.                 when All_Col_Bits_On = 0 and new_Bit_On = 1 then '(New)'
  7579.             end
  7580.             from    #t1_Prots
  7581.             where    ObjType    IN ('S ' ,'U ', 'V ')
  7582.             and    Type1Code = '1Regul'
  7583.             and   NOT (All_Col_Bits_On = 0 and new_Bit_On = 0)
  7584.  
  7585.  
  7586.             /* Expand and Insert individual column permission rows */
  7587.             INSERT    into   #t1_Prots
  7588.                 (Id
  7589.                 ,Type1Code
  7590.                 ,ObjType
  7591.                 ,ActionName
  7592.  
  7593.                 ,ActionCategory
  7594.                 ,ProtectTypeName
  7595.                 ,OwnerName
  7596.                 ,ObjectName
  7597.  
  7598.                 ,GranteeName
  7599.                 ,GrantorName
  7600.                 ,ColumnName
  7601.                 ,ColId    )
  7602.            SELECT    prot1.Id
  7603.                     ,'1Regul'
  7604.                     ,ObjType
  7605.                     ,ActionName
  7606.  
  7607.                     ,ActionCategory
  7608.                     ,ProtectTypeName
  7609.                     ,OwnerName
  7610.                     ,ObjectName
  7611.  
  7612.                     ,GranteeName
  7613.                     ,GrantorName
  7614.                     ,col_name ( prot1.Id ,val1.number )
  7615.                     ,val1.number
  7616.             from    #t1_Prots              prot1
  7617.                     ,master.dbo.spt_values  val1
  7618.                     ,syscolumns sysc
  7619.             where    prot1.ObjType    IN ('S ' ,'U ' ,'V ')
  7620.                 and    prot1.All_Col_Bits_On = 0
  7621.                 and prot1.Id    = sysc.id
  7622.                 and    val1.type   = 'P'
  7623.                 and    val1.number = sysc.colid
  7624.                 and
  7625.                 case convert(int,substring(prot1.Columns_Orig, 1, 1)) & 1
  7626.                     when 0 then convert(tinyint, substring(prot1.Columns_Orig, val1.low, 1))
  7627.                     else (~convert(tinyint, isnull(substring(prot1.Columns_Orig, val1.low, 1),0)))
  7628.                 end & val1.high <> 0
  7629.  
  7630.             delete from #t1_Prots
  7631.                     where    ObjType    IN ('S ' ,'U ' ,'V ')
  7632.                             and    All_Col_Bits_On = 0
  7633.                             and new_Bit_On = 0
  7634.         end
  7635.     end
  7636.  
  7637.  
  7638.     /* Handle statement permissions here*/
  7639.     IF (charindex('S',@permissionarea) > 0)
  7640.     begin
  7641.        /*    All statement permissions are 2Simpl */
  7642.         INSERT    #t1_Prots
  7643.              (    Id
  7644.                 ,Type1Code
  7645.                 ,ObjType
  7646.                 ,ActionName
  7647.  
  7648.                 ,ActionCategory
  7649.                 ,ProtectTypeName
  7650.                 ,Columns_Orig
  7651.                 ,OwnerName
  7652.  
  7653.                 ,ObjectName
  7654.                 ,GranteeName
  7655.                 ,GrantorName
  7656.                 ,ColumnName
  7657.  
  7658.                 ,ColId
  7659.                 ,Max_ColId
  7660.                 ,All_Col_Bits_On
  7661.                 ,new_Bit_On    )
  7662.         SELECT    id
  7663.                 ,'2Simpl'
  7664.                 ,Null
  7665.                 ,val1.name
  7666.  
  7667.                 ,'St'
  7668.                 ,val2.name
  7669.                 ,columns
  7670.                 ,'.'
  7671.  
  7672.                 ,'.'
  7673.                 ,user_name(sysp.uid)
  7674.                 ,user_name(sysp.grantor)
  7675.                 ,'.'
  7676.                 ,-123
  7677.  
  7678.                 ,Null
  7679.                 ,Null
  7680.                 ,Null
  7681.         FROM    sysprotects                sysp
  7682.                 ,master.dbo.spt_values    val1
  7683.                 ,master.dbo.spt_values  val2
  7684.         where    (@username is null or user_name(sysp.uid) = @username)
  7685.             and    (@grantorname is null or user_name(sysp.grantor) = @grantorname)
  7686.             and    val1.type     = 'T'
  7687.             and    val1.number   =  sysp.action
  7688.             and    (@ObjectStatementName is null or val1.name = @ObjectStatementName)
  7689.             and    val2.number   = sysp.protecttype
  7690.             and    val2.type     = 'T'
  7691.             and sysp.id = 0
  7692.     end
  7693.  
  7694.  
  7695.     IF NOT EXISTS (SELECT * From #t1_Prots)
  7696.     begin
  7697.         raiserror(15330,-1,-1)
  7698.         return (1)
  7699.     end
  7700.  
  7701.  
  7702.     /*    Calculate dynamic display col widths        */
  7703.     SELECT
  7704.     @charMaxLenOwner       =
  7705.         convert ( varchar, max(datalength(OwnerName)))
  7706.  
  7707.     ,@charMaxLenObject      =
  7708.         convert ( varchar, max(datalength(ObjectName)))
  7709.  
  7710.     ,@charMaxLenGrantee     =
  7711.         convert ( varchar, max(datalength(GranteeName)))
  7712.  
  7713.     ,@charMaxLenGrantor     =
  7714.         convert ( varchar, max(datalength(GrantorName)))
  7715.  
  7716.     ,@charMaxLenAction      =
  7717.         convert ( varchar, max(datalength(ActionName)))
  7718.  
  7719.     ,@charMaxLenColumnName  =
  7720.         convert ( varchar, max(datalength(ColumnName)))
  7721.     from    #t1_Prots
  7722.  
  7723.  
  7724. /*  Output the report    */
  7725. EXECUTE(
  7726. 'Set nocount off
  7727.  
  7728. SELECT    ''Owner''        = substring (OwnerName   ,1 ,' + @charMaxLenOwner   + ')
  7729.  
  7730.         ,''Object''        = substring (ObjectName  ,1 ,' + @charMaxLenObject  + ')
  7731.  
  7732.         ,''Grantee''    = substring (GranteeName ,1 ,' + @charMaxLenGrantee + ')
  7733.  
  7734.         ,''Grantor''    = substring (GrantorName ,1 ,' + @charMaxLenGrantor + ')
  7735.  
  7736.         ,''ProtectType''= ProtectTypeName
  7737.  
  7738.         ,''Action''        = substring (ActionName ,1 ,' + @charMaxLenAction + ')
  7739.  
  7740.         ,''Column''        = substring (ColumnName ,1 ,' + @charMaxLenColumnName + ')
  7741.    from    #t1_Prots
  7742.    order by
  7743.         ActionCategory
  7744.         ,Owner                ,Object
  7745.         ,Grantee            ,Grantor
  7746.         ,ProtectType        ,Action
  7747.         ,ColId  --Multiple  -123s  ( <0 )  possible
  7748.  
  7749. Set nocount on'
  7750. )
  7751.  
  7752. Return (0) -- sp_helprotect
  7753. go
  7754.  
  7755. checkpoint
  7756. go
  7757.  
  7758. raiserror(15339,-1,-1,'sp_helptext')
  7759. go
  7760. create procedure sp_helptext --- 1996/04/08 00:00
  7761. @objname nvarchar(776)
  7762. ,@columnname sysname = NULL
  7763. as
  7764.  
  7765. set nocount on
  7766.  
  7767. declare @dbname sysname
  7768. ,@BlankSpaceAdded   int
  7769. ,@BasePos       int
  7770. ,@CurrentPos    int
  7771. ,@TextLength    int
  7772. ,@LineId        int
  7773. ,@AddOnLen      int
  7774. ,@LFCR          int --lengths of line feed carriage return
  7775. ,@DefinedLength int
  7776.  
  7777. /* NOTE: Length of @SyscomText is 4000 to replace the length of
  7778. ** text column in syscomments.
  7779. ** lengths on @Line, #CommentText Text column and
  7780. ** value for @DefinedLength are all 255. These need to all have
  7781. ** the same values. 255 was selected in order for the max length
  7782. ** display using down level clients
  7783. */
  7784. ,@SyscomText    nvarchar(4000)
  7785. ,@Line          nvarchar(255)
  7786.  
  7787. Select @DefinedLength = 255
  7788. SELECT @BlankSpaceAdded = 0 /*Keeps track of blank spaces at end of lines. Note Len function ignores
  7789.                              trailing blank spaces*/
  7790. CREATE TABLE #CommentText
  7791. (LineId    int
  7792.  ,Text  nvarchar(255) collate database_default)
  7793.  
  7794. /*
  7795. **  Make sure the @objname is local to the current database.
  7796. */
  7797. select @dbname = parsename(@objname,3)
  7798.  
  7799. if @dbname is not null and @dbname <> db_name()
  7800.         begin
  7801.                 raiserror(15250,-1,-1)
  7802.                 return (1)
  7803.         end
  7804.  
  7805. /*
  7806. **  See if @objname exists.
  7807. */
  7808. if (object_id(@objname) is null)
  7809.         begin
  7810.         select @dbname = db_name()
  7811.         raiserror(15009,-1,-1,@objname,@dbname)
  7812.                 return (1)
  7813.         end
  7814.  
  7815. -- If second parameter was given.
  7816. if ( @columnname is not null)
  7817.     begin
  7818.         -- Check if it is a table
  7819.         if (select count(*) from sysobjects where id = object_id(@objname) and xtype in ('S ','U ','TF'))=0
  7820.             begin
  7821.                 raiserror(15218,-1,-1,@objname)
  7822.                 return(1)
  7823.             end
  7824.         -- check if it is a correct column name
  7825.         if ((select 'count'=count(*) from syscolumns where name = @columnname and id = object_id(@objname) and number = 0) =0)
  7826.             begin
  7827.                 raiserror(15645,-1,-1,@columnname)
  7828.                 return(1)
  7829.             end
  7830.     if ((select iscomputed from syscolumns where name = @columnname and id = object_id(@objname) and number = 0) = 0)
  7831.         begin
  7832.             raiserror(15646,-1,-1,@columnname)
  7833.             return(1)
  7834.         end
  7835.  
  7836.         DECLARE ms_crs_syscom  CURSOR LOCAL
  7837.         FOR SELECT text FROM syscomments WHERE id = object_id(@objname) and encrypted = 0 and number =
  7838.                         (select colid from syscolumns where name = @columnname and id = object_id(@objname) and number = 0)
  7839.                         order by number,colid
  7840.         FOR READ ONLY
  7841.  
  7842.     end
  7843. else
  7844.     begin
  7845.         /*
  7846.         **  Find out how many lines of text are coming back,
  7847.         **  and return if there are none.
  7848.         */
  7849.         if (select count(*) from syscomments c, sysobjects o where o.xtype not in ('S', 'U')
  7850.             and o.id = c.id and o.id = object_id(@objname)) = 0
  7851.                 begin
  7852.                         raiserror(15197,-1,-1,@objname)
  7853.                         return (1)
  7854.                 end
  7855.  
  7856.         if (select count(*) from syscomments where id = object_id(@objname)
  7857.             and encrypted = 0) = 0
  7858.                 begin
  7859.                         raiserror(15471,-1,-1)
  7860.                         return (0)
  7861.                 end
  7862.  
  7863.         DECLARE ms_crs_syscom  CURSOR LOCAL
  7864.         FOR SELECT text FROM syscomments WHERE id = OBJECT_ID(@objname) and encrypted = 0
  7865.                 ORDER BY number, colid
  7866.         FOR READ ONLY
  7867.     end
  7868.  
  7869. /*
  7870. **  Else get the text.
  7871. */
  7872. SELECT @LFCR = 2
  7873. SELECT @LineId = 1
  7874.  
  7875.  
  7876. OPEN ms_crs_syscom
  7877.  
  7878. FETCH NEXT FROM ms_crs_syscom into @SyscomText
  7879.  
  7880. WHILE @@fetch_status >= 0
  7881. BEGIN
  7882.  
  7883.     SELECT  @BasePos    = 1
  7884.     SELECT  @CurrentPos = 1
  7885.     SELECT  @TextLength = LEN(@SyscomText)
  7886.  
  7887.     WHILE @CurrentPos  != 0
  7888.     BEGIN
  7889.         --Looking for end of line followed by carriage return
  7890.         SELECT @CurrentPos =   CHARINDEX(char(13)+char(10), @SyscomText, @BasePos)
  7891.  
  7892.         --If carriage return found
  7893.         IF @CurrentPos != 0
  7894.         BEGIN
  7895.             /*If new value for @Lines length will be > then the
  7896.             **set length then insert current contents of @line
  7897.             **and proceed.
  7898.             */
  7899.             While (isnull(LEN(@Line),0) + @BlankSpaceAdded + @CurrentPos-@BasePos + @LFCR) > @DefinedLength
  7900.             BEGIN
  7901.                 SELECT @AddOnLen = @DefinedLength-(isnull(LEN(@Line),0) + @BlankSpaceAdded)
  7902.                 INSERT #CommentText VALUES
  7903.                 ( @LineId,
  7904.                   isnull(@Line, N'') + isnull(SUBSTRING(@SyscomText, @BasePos, @AddOnLen), N''))
  7905.                 SELECT @Line = NULL, @LineId = @LineId + 1,
  7906.                        @BasePos = @BasePos + @AddOnLen, @BlankSpaceAdded = 0
  7907.             END
  7908.             SELECT @Line    = isnull(@Line, N'') + isnull(SUBSTRING(@SyscomText, @BasePos, @CurrentPos-@BasePos + @LFCR), N'')
  7909.             SELECT @BasePos = @CurrentPos+2
  7910.             INSERT #CommentText VALUES( @LineId, @Line )
  7911.             SELECT @LineId = @LineId + 1
  7912.             SELECT @Line = NULL
  7913.         END
  7914.         ELSE
  7915.         --else carriage return not found
  7916.         BEGIN
  7917.             IF @BasePos <= @TextLength
  7918.             BEGIN
  7919.                 /*If new value for @Lines length will be > then the
  7920.                 **defined length
  7921.                 */
  7922.                 While (isnull(LEN(@Line),0) + @BlankSpaceAdded + @TextLength-@BasePos+1 ) > @DefinedLength
  7923.                 BEGIN
  7924.                     SELECT @AddOnLen = @DefinedLength - (isnull(LEN(@Line),0)  + @BlankSpaceAdded )
  7925.                     INSERT #CommentText VALUES
  7926.                     ( @LineId,
  7927.                       isnull(@Line, N'') + isnull(SUBSTRING(@SyscomText, @BasePos, @AddOnLen), N''))
  7928.                     SELECT @Line = NULL, @LineId = @LineId + 1,
  7929.                         @BasePos = @BasePos + @AddOnLen, @BlankSpaceAdded = 0
  7930.                 END
  7931.                 SELECT @Line = isnull(@Line, N'') + isnull(SUBSTRING(@SyscomText, @BasePos, @TextLength-@BasePos+1 ), N'')
  7932.                 if LEN(@Line) < @DefinedLength and charindex(' ', @SyscomText, @TextLength+1 ) > 0
  7933.                 BEGIN
  7934.                     SELECT @Line = @Line + ' ', @BlankSpaceAdded = 1
  7935.                 END
  7936.             END
  7937.         END
  7938.     END
  7939.  
  7940.     FETCH NEXT FROM ms_crs_syscom into @SyscomText
  7941. END
  7942.  
  7943. IF @Line is NOT NULL
  7944.     INSERT #CommentText VALUES( @LineId, @Line )
  7945.  
  7946. select Text from #CommentText order by LineId
  7947.  
  7948. CLOSE  ms_crs_syscom
  7949. DEALLOCATE     ms_crs_syscom
  7950.  
  7951. DROP TABLE     #CommentText
  7952.  
  7953. return (0) -- sp_helptext
  7954. go
  7955.  
  7956.  
  7957. --Running this create AFTER create sp_helpgroup.
  7958. raiserror(15339,-1,-1,'sp_helpuser')
  7959. go
  7960. CREATE PROCEDURE sp_helpuser  --- 1996/08/14 10:33
  7961.     @name_in_db       sysname    = NULL --User,Group,Alias
  7962. AS
  7963.  
  7964. Set nocount on
  7965. Set ansi_warnings off
  7966.  
  7967. Declare
  7968.     @RetCode               int
  7969.    ,@_rowcount             int
  7970.  
  7971. Declare
  7972.     @charMaxLen_UsName     varchar(11)
  7973.    ,@charMaxLen_GrName     varchar(11)
  7974.    ,@charMaxLen_LoName     varchar(11)
  7975.    ,@charMaxLen_DbName     varchar(11)
  7976.  
  7977. Declare
  7978.     @Name1Type             char(2)
  7979.    ,@CMaxUsUID             smallint
  7980.  
  7981. -----------------------  create holding table  --------------------
  7982. /*Create temp table before any DML to ensure dynamic*/
  7983.  
  7984. Create Table #tb1_uga
  7985.    (
  7986.     zUserName        sysname        collate database_default Null
  7987.    ,zGroupName       sysname        collate database_default Null
  7988.    ,zLoginName       sysname        collate database_default Null
  7989.    ,zDefDBName       sysname        collate database_default Null
  7990.    ,zUID             smallint       Null
  7991.    ,zSID             varbinary(85)  Null
  7992.    )
  7993.  
  7994. --------
  7995.  
  7996. Select
  7997.     @RetCode               = 0
  7998.    ,@Name1Type             = Null
  7999.    ,@CMaxUsUID               = 16383
  8000.  
  8001.  
  8002. -------------  What type of value (U,G,A) was input?  --------------
  8003.  
  8004. -------- NULL
  8005.  
  8006. IF (@name_in_db IS Null)
  8007.    begin
  8008.  
  8009.    Select @Name1Type = '-'
  8010.  
  8011.  
  8012.    INSERT into  #tb1_uga
  8013.                (
  8014.                 zUserName
  8015.                ,zGroupName
  8016.                ,zLoginName
  8017.                ,zDefDBName
  8018.                ,zUID
  8019.                ,zSID
  8020.                )
  8021.       SELECT
  8022.                    usu.name
  8023.                   ,case
  8024.                     when (usg.uid is null) then 'public'
  8025.                     else usg.name
  8026.                    end
  8027.                   ,lo.loginname
  8028.                   ,lo.dbname
  8029.                   ,usu.uid
  8030.                   ,usu.sid
  8031.          from
  8032.                    sysusers    usu left outer join
  8033.                     (sysmembers mem inner join sysusers usg on mem.groupuid = usg.uid) on usu.uid = mem.memberuid
  8034.                    left outer join master.dbo.syslogins  lo on usu.sid = lo.sid
  8035.          where
  8036.                    (usu.islogin = 1 and usu.isaliased = 0 and usu.hasdbaccess = 1) and
  8037.                    (usg.issqlrole = 1 or usg.uid is null)
  8038.  
  8039.  
  8040.    GOTO LABEL_25NAME1TYPEKNOWN
  8041.  
  8042.    end
  8043.  
  8044.  
  8045. -------- USER
  8046.  
  8047. INSERT   into   #tb1_uga
  8048.                (
  8049.                 zUserName
  8050.                ,zGroupName
  8051.                ,zLoginName
  8052.                ,zDefDBName
  8053.                ,zUID
  8054.                ,zSID
  8055.                )
  8056.       SELECT
  8057.                    usu.name
  8058.                   ,case
  8059.                     when (usg.uid is null) then 'public'
  8060.                     else usg.name
  8061.                    end
  8062.                   ,lo.loginname
  8063.                   ,lo.dbname
  8064.                   ,usu.uid
  8065.                   ,usu.sid
  8066.          from
  8067.                    sysusers    usu left outer join
  8068.                     (sysmembers mem inner join sysusers usg on mem.groupuid = usg.uid) on usu.uid = mem.memberuid
  8069.                    left outer join master.dbo.syslogins  lo on usu.sid = lo.sid
  8070.          where
  8071.                    (usu.islogin = 1 and usu.isaliased = 0 and usu.hasdbaccess = 1) and
  8072.                    (usg.issqlrole = 1 or usg.uid is null) and
  8073.                    usu.name    = @name_in_db
  8074.  
  8075.  
  8076. Select @_rowcount = @@rowcount
  8077.  
  8078.  
  8079. IF (@_rowcount > 0)
  8080.    begin
  8081.    Select @Name1Type = 'US'
  8082.  
  8083.    GOTO LABEL_25NAME1TYPEKNOWN
  8084.  
  8085.    end
  8086.  
  8087.  
  8088.  -------- ALIAS
  8089.  
  8090. INSERT   into   #tb1_uga
  8091.                (
  8092.                 zUserName
  8093.                ,zGroupName
  8094.                ,zLoginName
  8095.                ,zDefDBName
  8096.                ,zUID
  8097.                ,zSID
  8098.                )
  8099.  
  8100.     SELECT
  8101.                    usu.name
  8102.                   ,case
  8103.                     when (usg.uid is null) then 'public'
  8104.                     else usg.name
  8105.                    end
  8106.                   ,lo.loginname
  8107.                   ,lo.dbname
  8108.                   ,usu.uid
  8109.                   ,usu.sid
  8110.          from       (SELECT sid, altuid FROM sysusers WHERE isaliased = 1) al inner join
  8111.                    (sysusers    usu left outer join
  8112.                     (sysmembers mem inner join sysusers usg on mem.groupuid = usg.uid) on usu.uid = mem.memberuid
  8113.                    left outer join master.dbo.syslogins  lo on usu.sid = lo.sid) on al.altuid  = usu.uid
  8114.          where
  8115.                    (usu.islogin = 1 and usu.isaliased = 0) and
  8116.                    (usg.issqlrole = 1 or usg.uid is null) and
  8117.                    al.sid     = suser_sid(@name_in_db)
  8118.  
  8119.  
  8120. Select @_rowcount = @@rowcount
  8121.  
  8122.  
  8123. IF (@_rowcount > 0)
  8124.    begin
  8125.    Select @Name1Type = 'AL'
  8126.  
  8127.    GOTO LABEL_25NAME1TYPEKNOWN
  8128.  
  8129.    end
  8130.  
  8131.  
  8132. -------- GROUP
  8133. IF EXISTS
  8134.       (SELECT * FROM sysusers
  8135.          WHERE  name = @name_in_db
  8136.          AND (issqlrole = 1)
  8137.       )
  8138.    begin
  8139.    Select @Name1Type = 'GR'
  8140.  
  8141.    Execute sp_helpgroup @name_in_db
  8142.  
  8143.    GOTO LABEL_75FINAL  --Done
  8144.  
  8145.    end
  8146.  
  8147. -------- Error
  8148. Raiserror(15198,-1,-1 ,@name_in_db)  --Input Name is unfound
  8149. Select @RetCode = @RetCode | 1
  8150.  
  8151. GOTO LABEL_75FINAL
  8152.  
  8153. --------
  8154.  
  8155.  
  8156. LABEL_25NAME1TYPEKNOWN:
  8157.  
  8158.  
  8159. -----------------------  Printout the report  -------------------------
  8160.  
  8161. -------- Preparations for dynamic exec
  8162.  
  8163. SELECT
  8164.           @charMaxLen_UsName  = convert( varchar,
  8165.                   isnull( max( datalength( zUserName)),8))
  8166.  
  8167.          ,@charMaxLen_GrName  = convert( varchar,
  8168.                   isnull( max( datalength( zGroupName)),9))
  8169.  
  8170.          ,@charMaxLen_LoName  = convert( varchar,
  8171.                   isnull( max( datalength( zLoginName)),9))
  8172.  
  8173.          ,@charMaxLen_DbName  = convert( varchar,
  8174.                   isnull( max( datalength( zDefDBName)),9))
  8175.    from
  8176.           #tb1_uga
  8177.  
  8178.  
  8179. -------- Dynamic EXEC() to printout report
  8180.  
  8181.  
  8182. EXECUTE(
  8183. '
  8184. SELECT
  8185.              ''UserName''  =
  8186.                      substring(zUserName ,1,' + @charMaxLen_UsName + ')
  8187.  
  8188.             ,''GroupName'' =
  8189.                      substring(zGroupName,1,' + @charMaxLen_GrName + ')
  8190.  
  8191.             ,''LoginName'' =
  8192.                      substring(zLoginName,1,' + @charMaxLen_LoName + ')
  8193.  
  8194.             ,''DefDBName'' =
  8195.                      substring(zDefDBName,1,' + @charMaxLen_DbName + ')
  8196.  
  8197.             ,''UserID''    = convert(char(6),zUID)
  8198.  
  8199.             ,''SID''   = zSID
  8200.       from
  8201.              #tb1_uga
  8202.       order by
  8203.              1
  8204. '
  8205. )
  8206.  
  8207. -----------------------  A little extra nice-to-have
  8208.  
  8209. IF (@Name1Type IN ('-','US'))
  8210.    begin
  8211.  
  8212.    IF EXISTS (SELECT * FROM #tb1_uga tb1 ,(SELECT altuid FROM sysusers WHERE isaliased = 1) al, sysusers us
  8213.                        WHERE tb1.zUID = us.uid and us.uid = al.altuid
  8214.              )
  8215.       begin
  8216.  
  8217.       SELECT   'LoginName' = suser_sname(al.sid)
  8218.               ,'UserNameAliasedTo' = tb1.zUserName
  8219.          from  #tb1_uga tb1 ,(SELECT sid, altuid FROM sysusers WHERE isaliased = 1) al, sysusers us
  8220.          WHERE tb1.zUID = us.uid and us.uid = al.altuid
  8221.          order by 1
  8222.  
  8223.       end
  8224.    end
  8225.  
  8226.  
  8227. -----------------------  Finalization  ----------------------
  8228.  
  8229.  
  8230. LABEL_75FINAL:
  8231.  
  8232.  
  8233. IF (object_id('tempdb..#tb1_uga') IS not Null)
  8234.             Drop Table #tb1_uga
  8235.  
  8236. return (0) -- sp_helpuser
  8237. go
  8238.  
  8239.  
  8240. raiserror(15339,-1,-1,'sp_indexoption')
  8241. go
  8242. create procedure sp_indexoption
  8243.     @IndexNamePattern      nvarchar(776)
  8244.    ,@OptionName            varchar(35)
  8245.    ,@OptionValue           varchar(12)
  8246. as
  8247.     -- DECLARE VARIABLES
  8248.     DECLARE @tabid  int
  8249.             ,@indid  int
  8250.             ,@uid int
  8251.             ,@intOptionValue  int
  8252.             ,@flagbit  int
  8253.             ,@tablename  nvarchar(776)
  8254.  
  8255.     -- DISALLOW USER TRANSACTION --
  8256.     Set nocount on
  8257.     set implicit_transactions off
  8258.     IF @@trancount > 0
  8259.     begin
  8260.         raiserror(15002,-1,-1,'sp_indexoption')
  8261.         RETURN @@ERROR
  8262.     end
  8263.  
  8264.     -- VALIDATE OPTION VALUE
  8265.     SELECT @intOptionValue =
  8266.         CASE WHEN (lower(@OptionValue) in ('1' ,'on' ,'yes' ,'true')) THEN 1
  8267.             WHEN (lower(@OptionValue) in ('0' ,'off' ,'no' ,'false')) THEN 0
  8268.         ELSE NULL END
  8269.  
  8270.     -- CONVERT ANY OLD-STYLE PARAM TO NEW-STYLE, THEN VALIDATE OPTION NAME
  8271.     IF lower(@OptionName) IN ('allowrowlocks','allowpagelocks')
  8272.         SELECT @OptionName = 'dis'+@OptionName,
  8273.                 @intOptionValue = 1-@intOptionValue
  8274.     SELECT @flagbit = CASE lower(@OptionName) WHEN 'disallowrowlocks' THEN 1
  8275.                         WHEN 'disallowpagelocks' THEN 2
  8276.                         ELSE NULL END
  8277.  
  8278.     -- ERROR IF INVALID OPTION NAME OR VALUE
  8279.     IF @intOptionValue IS NULL OR @flagbit IS NULL
  8280.     begin
  8281.         raiserror(15600,-1,-1, 'sp_indexoption')
  8282.         RETURN @@ERROR
  8283.     end
  8284.  
  8285.     -- FIRST CHECK IF GIVEN AN TABLE NAME --
  8286.     SELECT @tabid = id, @uid = uid FROM sysobjects
  8287.         WHERE id = OBJECT_ID(@IndexNamePattern, 'local') AND xtype = 'U'
  8288.     IF @tabid IS NULL
  8289.     BEGIN
  8290.         -- NOW SEE IF WE HAVE TABLE.INDEX NAME, AND RESOLVE --
  8291.         SELECT @tablename =
  8292.                 IsNull(QuoteName(parsename(@IndexNamePattern, 4),'[')+'.','.') +
  8293.                 IsNull(QuoteName(parsename(@IndexNamePattern, 3),'[')+'.','.') +
  8294.                 IsNull(QuoteName(parsename(@IndexNamePattern, 2),'['),'')
  8295.         SELECT @tabid = OBJECT_ID(@tablename, 'U')
  8296.         SELECT @uid = ObjectProperty(@tabid, 'OwnerId'),
  8297.                 @indid = IndexProperty(@tabid, parsename(@IndexNamePattern, 1), 'IndexId')
  8298.         IF @indid IN (0,255)
  8299.             SELECT @indid = NULL
  8300.     END
  8301.     ELSE
  8302.         SELECT @tablename = @IndexNamePattern, @indid = 0    -- indicate all-indexes-for-table
  8303.  
  8304.     -- WE KNOW NOW IF WE HAVE A VALID TABLE/INDEX --
  8305.     IF @tabid IS NULL OR @uid IS NULL OR @indid IS NULL
  8306.     BEGIN
  8307.         raiserror(15388,-1,-1,@IndexNamePattern)
  8308.         RETURN @@ERROR
  8309.     END
  8310.  
  8311.     -- DO THE WORK (DBCC LOCKOBJECTSCHEMA will check permissions) --
  8312.     BEGIN TRAN
  8313.     DBCC LOCKOBJECTSCHEMA (@tablename)
  8314.     dbcc invalidate_textptr_objid(@tabid)    -- Invalidate inrow text pointers for table
  8315.     UPDATE sysindexes SET lockflags = (lockflags & ~@flagbit) | (@flagbit * @intOptionValue)
  8316.                 WHERE id = @tabid AND (indid = @indid OR @indid = 0)
  8317.     COMMIT TRAN
  8318.  
  8319.     -- RETURN SUCCESS
  8320.     RETURN 0 -- sp_indexoption
  8321. go
  8322.  
  8323. -------------------------------------------------------------
  8324.  
  8325. raiserror(15339,-1,-1,'sp_lock')
  8326. go
  8327. create procedure sp_lock --- 1996/04/08 00:00
  8328. @spid1 int = NULL,        /* server process id to check for locks */
  8329. @spid2 int = NULL        /* other process id to check for locks */
  8330. as
  8331.  
  8332. set nocount on
  8333. /*
  8334. **  Show the locks for both parameters.
  8335. */
  8336. if @spid1 is not NULL
  8337. begin
  8338.     select     convert (smallint, req_spid) As spid,
  8339.         rsc_dbid As dbid,
  8340.         rsc_objid As ObjId,
  8341.         rsc_indid As IndId,
  8342.         substring (v.name, 1, 4) As Type,
  8343.         substring (rsc_text, 1, 16) as Resource,
  8344.         substring (u.name, 1, 8) As Mode,
  8345.         substring (x.name, 1, 5) As Status
  8346.  
  8347.     from     master.dbo.syslockinfo,
  8348.         master.dbo.spt_values v,
  8349.         master.dbo.spt_values x,
  8350.         master.dbo.spt_values u
  8351.  
  8352.     where   master.dbo.syslockinfo.rsc_type = v.number
  8353.             and v.type = 'LR'
  8354.             and master.dbo.syslockinfo.req_status = x.number
  8355.             and x.type = 'LS'
  8356.             and master.dbo.syslockinfo.req_mode + 1 = u.number
  8357.             and u.type = 'L'
  8358.  
  8359.             and req_spid in (@spid1, @spid2)
  8360. end
  8361.  
  8362. /*
  8363. **  No parameters, so show all the locks.
  8364. */
  8365. else
  8366. begin
  8367.     select     convert (smallint, req_spid) As spid,
  8368.         rsc_dbid As dbid,
  8369.         rsc_objid As ObjId,
  8370.         rsc_indid As IndId,
  8371.         substring (v.name, 1, 4) As Type,
  8372.         substring (rsc_text, 1, 16) as Resource,
  8373.         substring (u.name, 1, 8) As Mode,
  8374.         substring (x.name, 1, 5) As Status
  8375.  
  8376.     from     master.dbo.syslockinfo,
  8377.         master.dbo.spt_values v,
  8378.         master.dbo.spt_values x,
  8379.         master.dbo.spt_values u
  8380.  
  8381.     where   master.dbo.syslockinfo.rsc_type = v.number
  8382.             and v.type = 'LR'
  8383.             and master.dbo.syslockinfo.req_status = x.number
  8384.             and x.type = 'LS'
  8385.             and master.dbo.syslockinfo.req_mode + 1 = u.number
  8386.             and u.type = 'L'
  8387.     order by spid
  8388. end
  8389.  
  8390. return (0) -- sp_lock
  8391. go
  8392.  
  8393. raiserror(15339,-1,-1,'sp_getapplock')
  8394. go
  8395. create procedure sp_getapplock --- 1999/04/14 00:00
  8396.  @Resource nvarchar (255) = NULL,           -- Resource to lock
  8397.  @LockMode varchar (32),                    -- Lock mode
  8398.  @LockOwner varchar (32) = 'Transaction',   -- Lock Owner - [D = Transaction]
  8399.  @LockTimeout int = NULL                    -- Lock timeout [D = Session setting]
  8400. as
  8401.  
  8402.   declare @mode integer
  8403.   declare @owner integer
  8404.   declare @result integer
  8405.   declare @dbid integer
  8406.  
  8407.   select @mode =
  8408.    CASE @LockMode
  8409.      When ('Shared')            Then 3
  8410.      When ('Update')            Then 4
  8411.      When ('Exclusive')         Then 5
  8412.      When ('IntentExclusive')   Then 8
  8413.      When ('IntentShared')      Then 6
  8414.      Else -1
  8415.    END
  8416.  
  8417.   if @mode = -1
  8418.   begin
  8419.     raiserror(15625, -1, -1, @LockMode, N'@LockMode')
  8420.     return (-999)
  8421.   end
  8422.  
  8423.   select @owner =
  8424.    CASE @LockOwner
  8425.     When ('Transaction')    Then 1
  8426.     When ('Session')        Then 3
  8427.     Else -1
  8428.    END
  8429.  
  8430.   if @owner = -1
  8431.   begin
  8432.     raiserror(15625, -1, -1, @LockOwner, N'@LockOwner')
  8433.     return (-999)
  8434.   end
  8435.  
  8436.   if @LockTimeout is null
  8437.   begin
  8438.     set @LockTimeout = @@LOCK_TIMEOUT
  8439.   end
  8440.  
  8441.   select @dbid = db_id ()
  8442.  
  8443.   if @owner = 1 and @@trancount = 0
  8444.   begin
  8445.     raiserror(15626, -1, -1)
  8446.     return (-999)
  8447.   end
  8448.  
  8449.   exec @result = master.dbo.xp_userlock 0, @dbid, @Resource, @mode, @owner, @LockTimeout
  8450.  
  8451.   return @result
  8452. go
  8453.  
  8454. checkpoint
  8455. go
  8456.  
  8457. raiserror(15339,-1,-1,'sp_releaseapplock')
  8458. go
  8459. create procedure sp_releaseapplock --- 1999/04/14 00:00
  8460.  @Resource nvarchar (255) = NULL,        -- Resource to unlock
  8461.  @LockOwner varchar (32) = 'Transaction'    -- Lock Owner - [D = Transaction]
  8462. as
  8463.  
  8464.   declare @owner integer
  8465.   declare @result integer
  8466.   declare @dbid integer
  8467.  
  8468.   select @owner =
  8469.     CASE @LockOwner
  8470.      When ('Transaction')   Then 1
  8471.      When ('Session')       Then 3
  8472.      Else -1
  8473.     END
  8474.  
  8475.   if @owner = -1
  8476.   begin
  8477.     raiserror(15625, -1, -1, @LockOwner, N'@LockOwner')
  8478.     return (-999)
  8479.   end
  8480.  
  8481.   select @dbid = db_id ()
  8482.  
  8483.   exec @result = master.dbo.xp_userlock 1, @dbid, @Resource, 0, @owner
  8484.  
  8485.   return @result
  8486. go
  8487.  
  8488.  
  8489.  
  8490. raiserror(15339,-1,-1,'sp_logdevice')
  8491. go
  8492. create procedure sp_logdevice
  8493. @dbname sysname,
  8494. @devicename sysname
  8495. as
  8496. declare @stmt nvarchar(1150)
  8497. declare @countrows int
  8498. declare @size nvarchar (10)
  8499. declare @maxsize nvarchar (10)
  8500. declare @growth nvarchar (10)
  8501. declare @filename sysname
  8502. set nocount on
  8503.  
  8504. -- Make sure the database exists
  8505. --
  8506. if not exists (select * from master.dbo.sysdatabases where name = @dbname)
  8507.     begin
  8508.         raiserror(15010,-1,-1,@dbname)
  8509.         return (1)
  8510.     end
  8511.  
  8512. -- Make sure the file exists and it should be in sysdevices as this is only
  8513. -- for older syntax.
  8514. --
  8515. if not exists (select * from master.dbo.sysdevices where name = @devicename)
  8516.     begin
  8517.         raiserror(15012,-1,-1,@devicename)
  8518.         return (1)
  8519.     end
  8520.  
  8521. -- Calculate the specs of the current file and save it into a temp table
  8522. --
  8523. create table #tempsize (size int, growth int, maxsize int, filename sysname collate database_default )
  8524. select @stmt = 'INSERT #tempsize SELECT size, growth, maxsize, filename FROM '
  8525.                 + @dbname + '.dbo.sysfiles WHERE name = '''
  8526.                 + @devicename + ''''
  8527. exec (@stmt)
  8528. select @countrows = count (*) from #tempsize
  8529.  
  8530. -- disconnect with devices and database
  8531. --
  8532. if @countrows <> 1
  8533.     begin
  8534.         raiserror(15012,-1,-1,@devicename)
  8535.         return (1)
  8536.     end
  8537.  
  8538. select @stmt = 'ALTER DATABASE ' + @dbname + ' REMOVE FILE ' + @devicename
  8539. exec (@stmt)
  8540. if @@error <> 0
  8541.     begin
  8542.         raiserror(15319,-1,-1,@dbname,@devicename)
  8543.         return(1)
  8544.     end
  8545. select @size = convert(nvarchar(10), size/128),
  8546.   @maxsize = convert(nvarchar(10), maxsize),
  8547.   @growth = convert(nvarchar(10), growth * 8),
  8548.   @filename = filename
  8549. from #tempsize
  8550.  
  8551. if (@maxsize = '-1')
  8552. begin
  8553.     select @maxsize = 'UNLIMITED'
  8554. end
  8555. else
  8556. begin
  8557.     select @maxsize = (convert (int, @maxsize)) / 128
  8558. end
  8559.  
  8560. select @stmt = 'ALTER DATABASE ' + @dbname
  8561.             + ' ADD LOG FILE (NAME = ['
  8562.             + @devicename + '], FILENAME = ['
  8563.             + @filename + '], SIZE = '
  8564.             + @size + ', MAXSIZE = '
  8565.             + @maxsize + ', FILEGROWTH = '
  8566.             + @growth + 'KB)'
  8567. exec (@stmt)
  8568. if @@error=0
  8569.       begin
  8570.       raiserror(15318,-1,-1,@dbname,@devicename)
  8571.       end
  8572. else
  8573.       begin
  8574.       raiserror(15319,-1,-1,@dbname,@devicename)
  8575.       return (1)
  8576.       end
  8577.  
  8578. return (0) -- sp_logdevice
  8579. GO
  8580.  
  8581.  
  8582. raiserror(15339,-1,-1,'sp_helpremotelogin')
  8583. go
  8584. create procedure sp_helpremotelogin --- 1996/04/08 00:00
  8585. @remoteserver sysname = NULL,    /* remote server name */
  8586. @remotename sysname = NULL        /* remote login name */
  8587. as
  8588. set nocount on
  8589.  
  8590. /*
  8591. **  If no server given, get 'em all.
  8592. */
  8593. if not exists (select * from master.dbo.sysservers s, master.dbo.sysremotelogins r
  8594.     where s.srvid = r.remoteserverid
  8595.         and (@remoteserver is null or s.srvname = @remoteserver ))
  8596.     begin
  8597.         if @remoteserver is null
  8598.             begin
  8599.                 raiserror(15200,-1,-1)
  8600.                 return (0)
  8601.             end
  8602.  
  8603.         raiserror(15201,-1,-1,@remoteserver)
  8604.         return (1)
  8605.     end
  8606.  
  8607. /*
  8608. **  If no remotename given, get 'em all.
  8609. */
  8610. if not exists (select * from master.dbo.sysremotelogins
  8611.     where (@remotename is null or isnull(remoteusername, ' ') = @remotename))
  8612.     begin
  8613.         if @remotename is null
  8614.             begin
  8615.                 raiserror(15202,-1,-1)
  8616.                 return (1)
  8617.             end
  8618.  
  8619.         raiserror(15203,-1,-1,@remotename)
  8620.         return (1)
  8621.  
  8622.     end
  8623.  
  8624. /*
  8625. **  Check for empty results.
  8626. */
  8627. if not exists (select *
  8628.     from master.dbo.sysremotelogins r, master.dbo.sysservers s
  8629.     where ( @remotename is null or isnull(r.remoteusername, ' ') = @remotename)
  8630.         and s.srvid = r.remoteserverid
  8631.         and (@remoteserver is null or s.srvname = @remoteserver))
  8632.     begin
  8633.         raiserror(15204,-1,-1,@remotename,@remoteserver)
  8634.         return (1)
  8635.     end
  8636.  
  8637. /*
  8638. **  Select the information.
  8639. */
  8640. select server = substring(s.srvname, 1, 22),
  8641.     local_user_name =
  8642.         substring(isnull(suser_sname(r.sid), '** use local name **'), 1, 22),
  8643.     remote_user_name =
  8644.         substring(isnull(r.remoteusername, '** mapped locally **'), 1, 22),
  8645.     options = case datalength(v.name)
  8646.                 when null then ''
  8647.                 when 0 then ''
  8648.                 else substring(v.name, 1, 9)
  8649.               end
  8650.         from master.dbo.sysservers s, master.dbo.sysremotelogins r,
  8651.             master.dbo.spt_values v
  8652.     where s.srvid = r.remoteserverid
  8653.         and (@remoteserver is null or s.srvname = @remoteserver)
  8654.         and (@remotename is null or isnull(r.remoteusername, ' ') = @remotename)
  8655.         and v.type = 'F'
  8656.         and v.number = r.status
  8657. order by server, remote_user_name
  8658.  
  8659. return (0) -- sp_helpremotelogin
  8660. go
  8661.  
  8662.  
  8663.  
  8664. raiserror(15339,-1,-1,'sp_helpsort')
  8665. go
  8666. create procedure sp_helpsort --- 1996/04/08 00:00
  8667. AS
  8668. set nocount on
  8669.  
  8670. /*
  8671. ** Now display the server default collation name
  8672. */
  8673. declare @servercollation sysname
  8674. select @servercollation = convert(sysname, serverproperty('collation'))
  8675.  
  8676. if @servercollation is not NULL
  8677.     BEGIN
  8678.     select 'Server default collation' = description
  8679.         from ::fn_helpcollations() C
  8680.         where @servercollation = C.name
  8681.     END
  8682.  
  8683. set nocount off
  8684. return(0) -- sp_helpsort
  8685. go
  8686.  
  8687.  
  8688. checkpoint
  8689. go
  8690.  
  8691.  
  8692. raiserror(15339,-1,-1,'sp_helpsql')
  8693. go
  8694.  
  8695. create procedure sp_helpsql
  8696. @in_command varchar(30) = NULL
  8697. AS
  8698. print 'SP_HELPSQL is not supported in this release, please refer to Online Help.'
  8699. return(0)
  8700. go
  8701.  
  8702.  
  8703. raiserror(15339,-1,-1,'sp_monitor')
  8704. go
  8705. create procedure sp_monitor --- 1996/04/08 00:00
  8706. as
  8707.  
  8708. /*
  8709. **  Declare variables to be used to hold current monitor values.
  8710. */
  8711. declare @now         datetime
  8712. declare @cpu_busy     int
  8713. declare @io_busy    int
  8714. declare @idle        int
  8715. declare @pack_received    int
  8716. declare @pack_sent    int
  8717. declare @pack_errors    int
  8718. declare @connections    int
  8719. declare @total_read    int
  8720. declare @total_write    int
  8721. declare @total_errors    int
  8722.  
  8723. declare @oldcpu_busy     int    /* used to see if DataServer has been rebooted */
  8724. declare @interval    int
  8725. declare @mspertick    int    /* milliseconds per tick */
  8726.  
  8727. /*
  8728. **  If we're in a transaction, disallow this since it might make recovery
  8729. **  impossible.
  8730. */
  8731. set implicit_transactions off
  8732. if @@trancount > 0
  8733.     begin
  8734.         raiserror(15002,-1,-1,'sp_monitor')
  8735.         return (1)
  8736.     end
  8737.  
  8738. /*
  8739. **  Set @mspertick.  This is just used to make the numbers easier to handle
  8740. **  and avoid overflow.
  8741. */
  8742. select @mspertick = convert(int, @@timeticks / 1000.0)
  8743.  
  8744. /*
  8745. **  Get current monitor values.
  8746. */
  8747. select
  8748.     @now = getdate(),
  8749.     @cpu_busy = @@cpu_busy,
  8750.     @io_busy = @@io_busy,
  8751.     @idle = @@idle,
  8752.     @pack_received = @@pack_received,
  8753.     @pack_sent = @@pack_sent,
  8754.     @connections = @@connections,
  8755.     @pack_errors = @@packet_errors,
  8756.     @total_read = @@total_read,
  8757.     @total_write = @@total_write,
  8758.     @total_errors = @@total_errors
  8759.  
  8760. /*
  8761. **  Check to see if DataServer has been rebooted.  If it has then the
  8762. **  value of @@cpu_busy will be less than the value of spt_monitor.cpu_busy.
  8763. **  If it has update spt_monitor.
  8764. */
  8765. select @oldcpu_busy = cpu_busy
  8766.     from master.dbo.spt_monitor
  8767. if @oldcpu_busy > @cpu_busy
  8768. begin
  8769.     update master.dbo.spt_monitor
  8770.         set
  8771.             lastrun = @now,
  8772.             cpu_busy = @cpu_busy,
  8773.             io_busy = @io_busy,
  8774.             idle = @idle,
  8775.             pack_received = @pack_received,
  8776.             pack_sent = @pack_sent,
  8777.             connections = @connections,
  8778.             pack_errors = @pack_errors,
  8779.             total_read = @total_read,
  8780.             total_write = @total_write,
  8781.             total_errors = @total_errors
  8782. end
  8783.  
  8784. /*
  8785. **  Now print out old and new monitor values.
  8786. */
  8787. set nocount on
  8788. select @interval = datediff(ss, lastrun, @now)
  8789.     from master.dbo.spt_monitor
  8790. /* To prevent a divide by zero error when run for the first
  8791. ** time after boot up
  8792. */
  8793. if @interval = 0
  8794.     select @interval = 1
  8795. select last_run = lastrun, current_run = @now, seconds = @interval
  8796.     from master.dbo.spt_monitor
  8797.  
  8798. select
  8799.     cpu_busy = substring(convert(varchar(11),
  8800.         convert(int, ((@cpu_busy * @mspertick) / 1000)))
  8801.         + '('
  8802.         + convert(varchar(11), convert(int, (((@cpu_busy - cpu_busy)
  8803.         * @mspertick) / 1000)))
  8804.         + ')'
  8805.         + '-'
  8806.         + convert(varchar(11), convert(int, ((((@cpu_busy - cpu_busy)
  8807.         * @mspertick) / 1000) * 100) / @interval))
  8808.         + '%',
  8809.         1, 25),
  8810.     io_busy = substring(convert(varchar(11),
  8811.         convert(int, ((@io_busy * @mspertick) / 1000)))
  8812.         + '('
  8813.         + convert(varchar(11), convert(int, (((@io_busy - io_busy)
  8814.         * @mspertick) / 1000)))
  8815.         + ')'
  8816.         + '-'
  8817.         + convert(varchar(11), convert(int, ((((@io_busy - io_busy)
  8818.         * @mspertick) / 1000) * 100) / @interval))
  8819.         + '%',
  8820.         1, 25),
  8821.     idle = substring(convert(varchar(11),
  8822.         convert(int, ((convert(bigint,@idle) * @mspertick) / 1000)))
  8823.         + '('
  8824.         + convert(varchar(11), convert(int, (((@idle - idle)
  8825.         * @mspertick) / 1000)))
  8826.         + ')'
  8827.         + '-'
  8828.         + convert(varchar(11), convert(int, ((((@idle - idle)
  8829.         * @mspertick) / 1000) * 100) / @interval))
  8830.         + '%',
  8831.         1, 25)
  8832. from master.dbo.spt_monitor
  8833.  
  8834. select
  8835.     packets_received = substring(convert(varchar(11), @pack_received) + '(' +
  8836.         convert(varchar(11), @pack_received - pack_received) + ')', 1, 25),
  8837.     packets_sent = substring(convert(varchar(11), @pack_sent) + '(' +
  8838.         convert(varchar(11), @pack_sent - pack_sent) + ')', 1, 25),
  8839.     packet_errors = substring(convert(varchar(11), @pack_errors) + '(' +
  8840.         convert(varchar(11), @pack_errors - pack_errors) + ')', 1, 25)
  8841. from master.dbo.spt_monitor
  8842.  
  8843. select
  8844.     total_read = substring(convert(varchar(11), @total_read) + '(' +
  8845.         convert(varchar(11), @total_read - total_read) + ')', 1, 19),
  8846.     total_write = substring(convert(varchar(11), @total_write) + '(' +
  8847.         convert(varchar(11), @total_write - total_write) + ')', 1, 19),
  8848.     total_errors = substring(convert(varchar(11), @total_errors) + '(' +
  8849.         convert(varchar(11), @total_errors - total_errors) + ')', 1, 19),
  8850.     connections = substring(convert(varchar(11), @connections) + '(' +
  8851.         convert(varchar(11), @connections - connections) + ')', 1, 18)
  8852. from master.dbo.spt_monitor
  8853.  
  8854. /*
  8855. **  Now update spt_monitor
  8856. */
  8857. update master.dbo.spt_monitor
  8858.     set
  8859.         lastrun = @now,
  8860.         cpu_busy = @cpu_busy,
  8861.         io_busy = @io_busy,
  8862.         idle = @idle,
  8863.         pack_received = @pack_received,
  8864.         pack_sent = @pack_sent,
  8865.         connections = @connections,
  8866.         pack_errors = @pack_errors,
  8867.         total_read = @total_read,
  8868.         total_write = @total_write,
  8869.         total_errors = @total_errors
  8870.  
  8871. return (0) -- sp_monitor
  8872. go
  8873.  
  8874. raiserror(15339,-1,-1,'sp_processmail')
  8875. go
  8876. create procedure sp_processmail --- 1996/06/19 17:30
  8877.     @subject varchar(255)=NULL,
  8878.     @filetype varchar(3)='txt',
  8879.     @separator varchar(3)='tab',
  8880.     @set_user varchar(132)='guest',
  8881.     @dbuse varchar(132)='master'
  8882. as
  8883.  
  8884. declare @status int
  8885. declare @msg_id varchar(94)
  8886. declare @originator varchar(255)
  8887. declare @cc_list varchar(255)
  8888. declare @msgsubject varchar(255)
  8889. declare @query varchar(8000)
  8890. declare @messages int
  8891. declare @mapifailure int
  8892. declare @resultmsg varchar(80)
  8893. declare @filename varchar(12)
  8894. declare @current_msg varchar(94)
  8895.  
  8896. select @messages=0
  8897. select @mapifailure=0
  8898.  
  8899. if @separator='tab' select @separator=CHAR(9)
  8900.  
  8901. /* get first message id */
  8902. exec @status = master.dbo.xp_findnextmsg
  8903.         @msg_id=@msg_id output,
  8904.         @unread_only='true'
  8905.  
  8906. if @status <> 0
  8907.     select @mapifailure=1
  8908.  
  8909. while (@mapifailure=0)
  8910.   begin
  8911.  
  8912.     if @msg_id is null break
  8913.     if @msg_id = '' break
  8914.  
  8915.     exec @status = master.dbo.xp_readmail
  8916.         @msg_id=@msg_id,
  8917.         @originator=@originator output,
  8918.         @cc_list=@cc_list output,
  8919.         @subject=@msgsubject output,
  8920.         @message=@query output,
  8921.         @peek='true',
  8922.  
  8923.         @suppress_attach='true'
  8924.  
  8925.     if @status <> 0
  8926.     begin
  8927.         select @mapifailure=1
  8928.         break
  8929.     end
  8930.  
  8931.     /* get new message id before processing & deleting current */
  8932.     select @current_msg=@msg_id
  8933.     exec @status = master.dbo.xp_findnextmsg
  8934.         @msg_id=@msg_id output,
  8935.         @unread_only='true'
  8936.  
  8937.         if @status <> 0
  8938.     begin
  8939.         select @mapifailure=1
  8940.     end
  8941.  
  8942.  
  8943.     if ((@subject IS NULL) OR (@subject=@msgsubject))
  8944.     begin
  8945.     /* generate random filename */
  8946.     select @filename='SQL' + convert(varchar,ROUND(RAND()*100000,0)) + '.' + @filetype
  8947.  
  8948.     exec @status = master.dbo.xp_sendmail
  8949.             @recipients=@originator,
  8950.             @copy_recipients=@cc_list,
  8951.             @message=@query,
  8952.             @query=@query,
  8953.             @subject='Query Results',
  8954.             @separator=@separator,
  8955.             @width=256,
  8956.             @attachments=@filename,
  8957.             @attach_results='true',
  8958.             @no_output='false',
  8959.             @echo_error='true',
  8960.             @set_user=@set_user,
  8961.             @dbuse=@dbuse
  8962.  
  8963.     if @status <> 0
  8964.         begin
  8965.             select @mapifailure=1
  8966.             break
  8967.         end
  8968.  
  8969.     select @messages=@messages+1
  8970.  
  8971.     exec master.dbo.xp_deletemail @current_msg
  8972.  
  8973.     end /* end of xp_sendmail block */
  8974.   end  /* end of xp_findnextmsg loop */
  8975.  
  8976.   /* finished examining the contents of inbox;  now send results */
  8977.   if @mapifailure=1
  8978.           begin
  8979.         raiserror(15079,-1,-1,@messages)
  8980.         return(1)
  8981.     end
  8982.   else
  8983.     return(0)
  8984. -- sp_processmail
  8985. go
  8986.  
  8987.  
  8988. raiserror(15339,-1,-1,'sp_recompile')
  8989. go
  8990. create procedure sp_recompile
  8991.     @objname         nvarchar(776)
  8992. as
  8993.     -- do sets and declares
  8994.     Set nocount on
  8995.     declare @objid      int,
  8996.             @curdbname  sysname
  8997.  
  8998.     -- CHECK VALIDITY OF OBJECT NAME --
  8999.     --  (1) Must exist in current database
  9000.     --  (2) Must be a table or an executable object
  9001.     select @objid = object_id(@objname, 'local')
  9002.     if @objid is null OR
  9003.         (ObjectProperty(@objid, 'IsTable') = 0 AND
  9004.          ObjectProperty(@objid, 'IsExecuted') = 0)
  9005.     begin
  9006.         select @curdbname = db_name()
  9007.         raiserror(15009,-1,-1 ,@objname, @curdbname)
  9008.         return @@error
  9009.     end
  9010.  
  9011.     -- CHECK PERMISSION --
  9012.     if (is_member('db_owner') = 0) AND (is_member('db_ddladmin') = 0)
  9013.         AND (is_member(user_name(ObjectProperty(@objid, 'ownerid'))) = 0)
  9014.     begin
  9015.         raiserror(15247,-1,-1)
  9016.         return @@error
  9017.     end
  9018.  
  9019.     -- BUMP SCHEMA FOR RECOMPILE --
  9020.     DBCC LockObjectSchema(@objname)
  9021.     if @@error <> 0
  9022.         return (1)
  9023.  
  9024.     -- TH-TH-TH-THAT'S IT!
  9025.     raiserror(15070,-1,-1,@objname)
  9026.     return (0) -- sp_recompile
  9027. go
  9028.  
  9029. checkpoint
  9030. go
  9031.  
  9032. raiserror(15339,-1,-1,'sp_remoteoption')
  9033. go
  9034. create procedure sp_remoteoption --- 1996/04/08 00:00
  9035.     @remoteserver sysname = NULL,    /* server name to change */
  9036.     @loginame sysname = NULL,        /* user's remote name */
  9037.     @remotename sysname = NULL,        /* user's local user name */
  9038.     @optname varchar(35) = NULL,        /* option name to turn on/off */
  9039.     @optvalue varchar(10) = NULL        /* true or false */
  9040. as
  9041.     declare @optcount int            /* number of options like @optname */
  9042.     declare @sid    varbinary(85)
  9043.  
  9044.     -- NO SERVER NAME? SHOW SETTABLE OPTION ('trusted')
  9045.     if @remoteserver is null
  9046.     begin
  9047.         raiserror(15473,-1,-1)
  9048.         select remotelogin_option = name from master.dbo.spt_values
  9049.             where type = 'F_U' and number = 16
  9050.         return (0)
  9051.     end
  9052.  
  9053.     -- NO USER XACT --
  9054.     set implicit_transactions off
  9055.     if @@trancount > 0
  9056.     begin
  9057.         raiserror(15002,-1,-1,'sp_remoteoption')
  9058.         return (1)
  9059.     end
  9060.  
  9061.     -- PERMISSIONS --
  9062.     if not (is_srvrolemember('securityadmin') = 1)
  9063.     begin
  9064.         raiserror(15247,-1,-1)
  9065.         return (1)
  9066.     end
  9067.  
  9068.     -- VALIDATE SERVER NAME --
  9069.     declare @srvid smallint
  9070.     select @srvid = srvid from master.dbo.sysservers where srvname = @remoteserver
  9071.     if @srvid is null
  9072.     begin
  9073.         raiserror(15015,-1,-1,@remoteserver)
  9074.         return (1)
  9075.     end
  9076.  
  9077.     -- VALIDATE @loginame --
  9078.     if @loginame is not null
  9079.     begin
  9080.         select @sid = sid from master.dbo.syslogins where loginname = @loginame
  9081.                     AND isntname = 0        -- cannot remap to NT login
  9082.         if @sid is null
  9083.         begin
  9084.             raiserror(15067,-1,-1,@loginame)
  9085.             return (1)
  9086.         end
  9087.     end
  9088.  
  9089.     -- VALIDATE <@sid, @remotename> PAIR FOR @srvid --
  9090.     if not exists (select * from master.dbo.sysxlogins where srvid = @srvid
  9091.                 and ((@remotename is null AND name is null) OR name = @remotename)
  9092.                 and ((@sid is null AND sid is null) OR sid = @sid))
  9093.     begin
  9094.         raiserror(15185,-1,-1,@remotename,@loginame,@remoteserver)
  9095.         return (1)
  9096.     end
  9097.  
  9098.     -- Check remaining parameters --
  9099.     if @optname is NULL or lower(@optvalue) not in ('true', 'false') or @optvalue is null
  9100.     begin
  9101.         raiserror(15220,-1,-1)
  9102.         return (1)
  9103.     end
  9104.  
  9105.     -- SEE IF @optname MATCHES THE 'trusted' OPTION --
  9106.     if not exists (select * from master.dbo.spt_values where name like '%' + @optname + '%'
  9107.             and type = 'F_U' and number = 16)
  9108.     begin
  9109.         raiserror(15221,-1,-1)
  9110.         return (1)
  9111.     end
  9112.  
  9113.     -- Now update sysremotelogins
  9114.     if lower(@optvalue) = 'true'
  9115.     begin
  9116.         update master.dbo.sysxlogins set xstatus = xstatus | 16, xdate1 = getdate()
  9117.             where srvid = @srvid
  9118.                 and ((@remotename is null AND name is null) OR name = @remotename)
  9119.                 and ((@sid is null AND sid is null) OR sid = @sid)
  9120.     end
  9121.     else    -- 'false'
  9122.     begin
  9123.         update master.dbo.sysxlogins set xstatus = xstatus & ~16, xdate1 = getdate()
  9124.             where srvid = @srvid
  9125.                 and ((@remotename is null AND name is null) OR name = @remotename)
  9126.                 and ((@sid is null AND sid is null) OR sid = @sid)
  9127.     end
  9128.     return (0) -- sp_remoteoption
  9129. go
  9130.  
  9131. checkpoint
  9132. go
  9133.  
  9134. raiserror(15339,-1,-1,'sp_invalidate_textptr')
  9135. go
  9136. create procedure sp_invalidate_textptr
  9137.     @TextPtrValue      varbinary(16) = 0x00
  9138. as
  9139.     dbcc invalidate_textptr(@TextPtrValue)
  9140.     return (0); -- sp_invalidate_textptr
  9141. go
  9142.  
  9143. raiserror(15339,-1,-1,'sp_tableoption')
  9144. go
  9145. create procedure sp_tableoption
  9146.     @TableNamePattern      nvarchar(776)
  9147.    ,@OptionName            varchar(35)
  9148.    ,@OptionValue           varchar(12)
  9149. as
  9150.     -- DECLARE AND INIT VARIABLES
  9151.     DECLARE @OPTpintable varchar(25)
  9152.             ,@OPTbulklock varchar(25)
  9153.             ,@OPTtextinrow varchar(25)
  9154.             ,@CurrentDBId int
  9155.             ,@TabId int
  9156.             ,@intOptionValue int
  9157.             ,@uid int
  9158.     SELECT @OPTpintable = 'pintable'
  9159.             ,@OPTbulklock = 'table lock on bulk load'
  9160.             ,@OPTtextinrow = 'text in row'
  9161.             ,@CurrentDBId = db_id()
  9162.  
  9163.     -- DISALLOW USER TRANSACTION (except for in 'text in row') --
  9164.     Set nocount on
  9165.     set implicit_transactions off
  9166.     IF (@@trancount > 0 AND lower(@OptionName) <> @OPTtextinrow)
  9167.     begin
  9168.         raiserror(15002,-1,-1,'sp_tableoption')
  9169.         RETURN @@ERROR
  9170.     end
  9171.  
  9172.     -- VALIDATE OPTION VALUE
  9173.     SELECT @intOptionValue =
  9174.         CASE WHEN (lower(@OptionValue) in ('1' ,'on' ,'yes' ,'true')) THEN 1
  9175.             WHEN (lower(@OptionValue) in ('0' ,'off' ,'no' ,'false')) THEN 0
  9176.             WHEN (lower(@OptionName) = @OPTtextinrow AND ISNUMERIC (@OptionValue) <> 0)
  9177.             THEN convert (int, @OptionValue)
  9178.         ELSE NULL END
  9179.  
  9180.     -- ERROR IF INVALID OPTION NAME OR VALUE
  9181.     IF @intOptionValue IS NULL OR
  9182.         (lower(@OptionName) NOT IN (@OPTpintable, @OPTbulklock, @OPTtextinrow))
  9183.     begin
  9184.         raiserror(15600,-1,-1, 'sp_tableoption')
  9185.         RETURN @@ERROR
  9186.     end
  9187.  
  9188.     -- VERIFY WE HAVE A USER-TABLE BY THIS NAME IN THE DATABASE
  9189.     SELECT @TabId = id, @uid = uid FROM sysobjects
  9190.         WHERE id = OBJECT_ID(@TableNamePattern, 'local') AND xtype = 'U'
  9191.     IF @TabId IS NULL
  9192.     begin
  9193.         raiserror(15388,-1,-1,@TableNamePattern)
  9194.         RETURN @@ERROR
  9195.     end
  9196.  
  9197.     -- Check standard Table-DDL permissions
  9198.     IF not (is_member('db_owner') = 1) and
  9199.         not (is_member('db_ddladmin') = 1) and
  9200.         not (is_member(user_name(@uid)) = 1)
  9201.     begin
  9202.         raiserror(15247,-1,-1)
  9203.         RETURN @@ERROR
  9204.     end
  9205.  
  9206.     -- HANDLE TEXT-IN-ROW option
  9207.     IF (lower(@OptionName) = @OPTtextinrow)
  9208.     begin
  9209.         -- Set according to value given (Note: dbcc no_textptr does proper schema-locking)
  9210.         if (@intOptionValue != 0 and @intOptionValue != 1 and
  9211.             (@intOptionValue < 24 or @intOptionValue > 7000))
  9212.         BEGIN    -- Invalid value
  9213.             raiserror (15112,-1,-1)
  9214.             RETURN @@ERROR
  9215.         END
  9216.  
  9217.         -- invalidate inrow text pointer for the table
  9218.         --
  9219.         dbcc invalidate_textptr_objid(@TabId)
  9220.  
  9221.         BEGIN TRAN
  9222.         DBCC LOCKOBJECTSCHEMA(@TableNamePattern)
  9223.         dbcc no_textptr(@TabId, @intOptionValue)
  9224.         COMMIT TRAN
  9225.     end
  9226.  
  9227.     -- HANDLE TABLOCK-ON-BCP option
  9228.     ELSE IF (lower(@OptionName) = @OPTbulklock)
  9229.     BEGIN
  9230.         -- Make required change
  9231.         IF ObjectProperty(@TabId, 'TableIsLockedOnBulkLoad') <> @intOptionValue
  9232.         BEGIN
  9233.             BEGIN TRAN
  9234.             DBCC LOCKOBJECTSCHEMA(@TableNamePattern)
  9235.             UPDATE sysobjects SET status = (status & ~134217728) | (134217728 * @intOptionValue)
  9236.                 WHERE id = @TabId
  9237.             COMMIT TRAN
  9238.         END
  9239.     END
  9240.  
  9241.     -- HANDLE PIN-TABLE option
  9242.     ELSE IF (lower(@OptionName) = @OPTpintable)
  9243.     BEGIN
  9244.         -- ADDITIONAL SECURITY: Must be sysadmin to pin pages
  9245.         IF (not (is_srvrolemember('sysadmin') = 1))
  9246.         begin
  9247.             raiserror(15247,-1,-1)
  9248.             RETURN @@ERROR
  9249.         end
  9250.  
  9251.         -- Make change if required
  9252.         IF ObjectProperty(@TabId, 'TableIsPinned') <> @intOptionValue
  9253.         BEGIN
  9254.             IF @intOptionValue = 1
  9255.                 DBCC pintable(@CurrentDBId, @TabId)
  9256.             ELSE
  9257.                 DBCC unpintable(@CurrentDBId, @TabId)
  9258.         END
  9259.     END
  9260.  
  9261.     -- Return success
  9262.     Return 0  --sp_tableoption
  9263. go
  9264.  
  9265. checkpoint
  9266. go
  9267.  
  9268. raiserror(15339,-1,-1,'sp_procoption')
  9269. go
  9270. create procedure sp_procoption
  9271.     @ProcName        nvarchar(776)
  9272.    ,@OptionName        varchar(35)
  9273.    ,@OptionValue    varchar(12)
  9274. as
  9275.     -- DECLARE VARIABLES
  9276.     DECLARE @tabid  int
  9277.             ,@uid int
  9278.             ,@intOptionValue  int
  9279.             ,@dbname sysname
  9280.  
  9281.     -- DISALLOW USER TRANSACTION --
  9282.     Set nocount on
  9283.     set implicit_transactions off
  9284.     IF @@trancount > 0
  9285.     begin
  9286.         raiserror(15002,-1,-1,'sp_procoption')
  9287.         RETURN @@ERROR
  9288.     end
  9289.  
  9290.     -- VALIDATE OPTION NAME AND VALUE
  9291.     SELECT @intOptionValue =
  9292.         CASE WHEN (lower(@OptionValue) in ('1' ,'on' ,'yes' ,'true')) THEN 1
  9293.             WHEN (lower(@OptionValue) in ('0' ,'off' ,'no' ,'false')) THEN 0
  9294.         ELSE NULL END
  9295.     IF @intOptionValue IS NULL OR @OptionName IS NULL OR lower(@OptionName) <> 'startup'
  9296.     BEGIN
  9297.         raiserror(15600,-1,-1, 'sp_procoption')
  9298.         RETURN @@ERROR
  9299.     END
  9300.  
  9301.     -- MUST BE sysadmin (Startup-procs run as sysadmin) --
  9302.     IF is_srvrolemember('sysadmin') = 0
  9303.     BEGIN
  9304.         raiserror(15247,-1,-1)
  9305.         RETURN @@ERROR
  9306.     END
  9307.  
  9308.     -- RESOLVE GIVEN OBJECT NAME --
  9309.     SELECT @tabid = id, @uid = uid FROM sysobjects
  9310.         WHERE id = OBJECT_ID(@ProcName, 'local') AND xtype IN ('X','P')
  9311.  
  9312.     -- VALID OBJECT IN DATABASE? --
  9313.     IF @tabid IS NULL
  9314.     BEGIN
  9315.         SELECT @dbname = db_name()
  9316.         raiserror(15009,-1,-1 ,@ProcName, @dbname)
  9317.         RETURN @@ERROR
  9318.     END
  9319.  
  9320.     -- STARTUP PROC MUST BE OWNED BY DBO IN MASTER --
  9321.     IF (db_id() <> 1 OR @uid <> 1)
  9322.     BEGIN
  9323.         raiserror(15398,-1,-1)
  9324.         RETURN @@ERROR
  9325.     END
  9326.  
  9327.     -- PROC CANNOT HAVE PARAMETERS --
  9328.     IF EXISTS ( SELECT * FROM syscolumns WHERE id = @tabid )
  9329.     BEGIN
  9330.         raiserror(15399,-1, -1)
  9331.         RETURN @@ERROR
  9332.     END
  9333.  
  9334.     -- Do the work
  9335.     BEGIN TRAN
  9336.     DBCC LockObjectSchema(@ProcName)
  9337.     UPDATE sysobjects SET status = (status & ~2) | (2 * @intOptionValue) WHERE id = @tabid
  9338.  
  9339.     -- Set Config option for startup procs
  9340.     UPDATE master.dbo.sysconfigures SET value =
  9341.             CASE WHEN EXISTS (SELECT * FROM sysobjects WHERE xtype IN ('X','P')
  9342.                 AND ObjectProperty(id, 'ExecIsStartup') = 1)
  9343.             THEN 1 ELSE 0 END
  9344.         WHERE config = 1547
  9345.  
  9346.     -- If no error, commit and reconfigure
  9347.     IF (@@error <> 0)
  9348.     BEGIN
  9349.         ROLLBACK TRAN
  9350.         RETURN 1
  9351.     END
  9352.     COMMIT TRAN
  9353.     RECONFIGURE WITH OVERRIDE
  9354.  
  9355.     -- RETURN SUCCESS
  9356.     RETURN 0 -- sp_procoption
  9357. go
  9358.  
  9359. checkpoint
  9360. go
  9361.  
  9362.  
  9363. raiserror(15339,-1,-1,'sp_renamedb')
  9364. go
  9365. create procedure sp_renamedb --- 1996/08/20 13:52
  9366. @dbname sysname,            /* old (current) db name */
  9367. @newname sysname            /* new name we want to call it */
  9368. as
  9369. -- Use sp_rename instead.
  9370. declare @objid int            /* object id of the thing to rename */
  9371. declare @bitdesc varchar(30)        /* bit description for the db */
  9372. declare @curdbid int            /* id of database to be changed */
  9373. declare @execstring nvarchar (4000)
  9374.  
  9375. /*
  9376. **  If we're in a transaction, disallow this since it might make recovery
  9377. **  impossible.
  9378. */
  9379. set implicit_transactions off
  9380. if @@trancount > 0
  9381.     begin
  9382.         raiserror(15002,-1,-1,'sp_renamedb')
  9383.         return (1)
  9384.     end
  9385.  
  9386. /*
  9387. **  Only the SA can do this.
  9388. */
  9389. if not (is_srvrolemember('dbcreator') = 1)
  9390.     begin
  9391.         raiserror(15247,-1,-1)
  9392.         return (1)
  9393.     end
  9394.  
  9395. /*
  9396. **  Make sure the database exists.
  9397. */
  9398. if not exists (select * from master.dbo.sysdatabases where name = @dbname)
  9399.     begin
  9400.         raiserror(15010,-1,-1,@dbname)
  9401.         return (1)
  9402.     end
  9403.  
  9404. /*
  9405. **  Make sure that the @newname db doesn't already exist.
  9406. */
  9407. if exists (select * from master.dbo.sysdatabases where name = @newname)
  9408.     begin
  9409.         raiserror(15032,-1,-1,@newname)
  9410.         return (1)
  9411.     end
  9412.  
  9413. /*
  9414. **  Check to see that the @newname is valid.
  9415. */
  9416. declare @returncode int
  9417. exec @returncode = sp_validname @newname
  9418. if @returncode <> 0
  9419. begin
  9420.     raiserror(15224,-1,15,@newname)
  9421.     return(1)
  9422. end
  9423.  
  9424. /*
  9425. **  Don't allow the names of master, tempdb, and model to be changed.
  9426. */
  9427. if @dbname in ('master', 'model', 'tempdb')
  9428.     begin
  9429.         raiserror(15227,-1,-1,@dbname)
  9430.         return (1)
  9431.     end
  9432.  
  9433.  
  9434.     select @execstring = 'ALTER DATABASE '
  9435.         + quotename( @dbname , '[')
  9436.         + ' MODIFY NAME = '
  9437.         + quotename( @newname , '[')
  9438.  
  9439.     exec (@execstring)
  9440.  
  9441. if @@error <>  0
  9442.     begin
  9443.         -- No need to raiserror as the CREATE DATABASE will do so
  9444.         return(1)
  9445.     end
  9446.  
  9447. return (0) -- sp_renamedb
  9448. go
  9449.  
  9450. raiserror(15339,-1,-1,'sp_remove_tempdb_file')
  9451. go
  9452. create procedure sp_remove_tempdb_file @filename sysname
  9453. as
  9454. declare @fileid smallint
  9455. set nocount on
  9456.  
  9457. select @fileid = fileid
  9458.     from sysaltfiles
  9459.     where dbid = 2  -- limit to tempdb files
  9460.     and name = @filename
  9461. if @fileid is null
  9462. begin
  9463.     -- file name does not exist
  9464.     raiserror(15311,-1,-1,@filename)
  9465.     return (1)
  9466. end
  9467. if @fileid < 3
  9468. begin
  9469.     -- file is one of the primary files
  9470.     raiserror(15312,-1,-1,@filename)
  9471.     return (1)
  9472. end
  9473.  
  9474. delete sysaltfiles where dbid = 2 and fileid = @fileid
  9475. if @@error>0
  9476.    begin
  9477.       raiserror(15321,-1,-1, @filename)
  9478.       return (1)
  9479.    end
  9480. else
  9481.    begin
  9482.       raiserror(15322,-1,-1, @filename)
  9483.       return (0)
  9484.    end
  9485.  
  9486. go
  9487.  
  9488.  
  9489. raiserror(15339,-1,-1,'sp_rename')
  9490. go
  9491. /*ANSI_NULLS on for  creation of sp_rename*/
  9492. Set ansi_nulls on
  9493. go
  9494. CREATE PROCEDURE sp_rename
  9495.     @objname    nvarchar(776),        -- up to 3-part "old" name
  9496.     @newname    sysname,            -- one-part new name
  9497.     @objtype    varchar(13) = null    -- identifying the name
  9498. as
  9499. /********1*********2*********3*********4*********5**
  9500. DOCUMENTATION:
  9501.    [1]  To rename a table, the @objname (meaning OldName) parm can be
  9502. passed in totally unqualified or fully qualified.
  9503.    [2]  The SA or DBO can rename objects owned by lesser users,
  9504. without the need for SetUser.
  9505.    [3]  The Owner portion of a qualified name can usually be
  9506. passed in in the omitted form (as in MyDb..MyTab or MyTab).  The
  9507. typical exception is when the SA/DBO is trying to rename a table
  9508. where the @objname is present twice in sysobjects as a table
  9509. owned only by two different lesser users; requiring an explicit
  9510. owner qualifier in @objname.
  9511.    [4]  An unspecified Owner qualifier will default to the
  9512. current user if doing so will either resolve what would
  9513. otherwise be an ambiguity within @objtype, or will result
  9514. in exactly one match.
  9515.    [5]  If Database is part of the qualified @objname,
  9516. then it must match the current database.  The @newname parm can
  9517. never be qualified.
  9518.    [6]  Here are the valid @objtype values.  They correspond to
  9519. system tables which track each type:
  9520.       'column'  'database'  'index'  'object'  'userdatatype'
  9521. The @objtype parm is sometimes required.  It is always required
  9522. for databases.  It is required whenever ambiguities would
  9523. otherwise exist.  Explicit use of @objtype is always encouraged.
  9524.    [7]  Parms can use quoted_identifiers.  For example:
  9525.    Execute sp_rename 'amy."his table"','"her table"','object'
  9526. *********1*********2*********3*********4*********5*/
  9527. Set nocount      on
  9528. Set ansi_padding on
  9529.  
  9530. Declare @objtypeIN        varchar(13),
  9531.         @ExecRC            integer,
  9532.         @CurrentDb        sysname,
  9533.         @CountNumNodes    integer,
  9534.         @UnqualOldName    sysname,
  9535.         @QualName1        sysname,
  9536.         @QualName2        sysname,
  9537.         @QualName3        sysname,
  9538.         @OwnAndObjName    nvarchar(517),    -- "[owner].[object]"
  9539.         @objid            integer,
  9540.         @xtype            nchar(2),
  9541.         @indid            smallint,
  9542.         @colid            smallint,
  9543.         @cnstid            integer,
  9544.         @parent_obj        integer,
  9545.         @xusertype        smallint,
  9546.         @ownerid        smallint,
  9547.         @objid_tmp        integer,
  9548.         @xtype_tmp        nchar(2),
  9549.         @retcode        int,
  9550.         @replinfo        int,
  9551.         @replbits        int
  9552. -- initial (non-null) settings
  9553. Select    @CurrentDb        = db_name(),
  9554.         @objtypeIN        = @objtype,
  9555.         @replbits        = 129    --Indicates table is used in replication
  9556.  
  9557. -- make type case insensitive
  9558. select @objtype = lower(@objtypeIN)
  9559.  
  9560. ------------------------------------------------------------------------
  9561. -------------------  PHASE 10:  Simple parm edits  ---------------------
  9562. ------------------------------------------------------------------------
  9563.  
  9564. -- Valid rename-type param?
  9565. IF (@objtype is not null AND
  9566.     @objtype not in ('column', 'database', 'index', 'object', 'userdatatype'))
  9567. begin
  9568.     raiserror(15249,-1,-1,@objtypeIN,0)
  9569.     return 1
  9570. end
  9571. -- null names?
  9572. IF (@newname IS null)
  9573. begin
  9574.     raiserror(15223,-1,11,'NewName')
  9575.     return 1
  9576. end
  9577. if (@objname IS null)
  9578. begin
  9579.     raiserror(15223,-1,-1,'OldName')
  9580.     return 1
  9581. end
  9582.  
  9583. ---------------  Is NewName minimally valid?
  9584.  
  9585. --Check for valid rename name
  9586. exec @retcode = sp_validname @newname
  9587. if @retcode <> 0
  9588. begin
  9589.     raiserror(15224,-1,15,@newname)
  9590.     return 1
  9591. end
  9592.  
  9593. -------- Parse apart the perhaps dots-qualified old name.
  9594.  
  9595. select @UnqualOldName = parsename(@objname, 1),
  9596.         @QualName1 = parsename(@objname, 2),
  9597.         @QualName2 = parsename(@objname, 3),
  9598.         @QualName3 = parsename(@objname, 4)
  9599. IF (@UnqualOldName IS Null)
  9600. begin
  9601.     raiserror(15253,-1,-1,@objname)
  9602.     return 1
  9603. end
  9604.  
  9605. -- count name parts --
  9606. select @CountNumNodes = CASE WHEN @QualName3 IS NOT NULL THEN 4
  9607.                              WHEN @QualName2 IS NOT NULL THEN 3
  9608.                              WHEN @QualName1 IS NOT NULL THEN 2
  9609.                              ELSE 1 END
  9610. IF (@objtype  = 'database' AND @CountNumNodes > 1)
  9611. begin
  9612.     Raiserror(15395,-1,20,@objtypeIN)
  9613.     return 1
  9614. end
  9615. if (@objtype in ('object','userdatatype') AND @CountNumNodes > 3)
  9616. begin
  9617.     raiserror(15225,-1,-1,@objname, @CurrentDb, @objtypeIN)
  9618.     return 1
  9619. end
  9620.  
  9621.  
  9622. ---------------------------------------------------------------------------
  9623. ----------------------  PHASE 20:  Settle Parm1ItemType  ------------------
  9624. ---------------------------------------------------------------------------
  9625.  
  9626. ------------- database?
  9627. IF (@objtype  = 'database')
  9628. begin
  9629.     execute @ExecRC = sp_renamedb @UnqualOldName ,@newname -- de-docu old sproc
  9630.     IF @ExecRC <> 0
  9631.         return 1
  9632.     GOTO LABEL_51_AFTERUPDATES
  9633. end
  9634.  
  9635. -- assuming column/index-name, obtain object/column id's
  9636. if @QualName2 is not null
  9637.     select @objid = object_id(QuoteName(@QualName2) +'.'+ QuoteName(@QualName1))
  9638. else
  9639.     select @objid = object_id(QuoteName(@QualName1))
  9640.  
  9641. select @xtype = xtype, @replinfo = replinfo from sysobjects where id = @objid
  9642.  
  9643. ------------ column?
  9644. if (@objtype = 'column' or @objtypeIN is null)
  9645. begin
  9646.     -- find column
  9647.     select @colid = NULL
  9648.     if (@xtype in ('U','V'))
  9649.         select @colid = colid from syscolumns
  9650.                 where id = @objid and name = @UnqualOldName
  9651.  
  9652.     -- check for wrong param
  9653.     if ((@colid is not null AND @objtype <> 'column') OR
  9654.         (@colid is null AND @objtype = 'column'))
  9655.     begin
  9656.         raiserror(15248,-1,-1,@objtypeIN)
  9657.         return 1
  9658.     end
  9659.  
  9660.     -- remember if we've found a column
  9661.     IF (@colid is not null)
  9662.     begin
  9663.         if (@replinfo & @replbits <> 0)
  9664.             begin
  9665.                 raiserror(15051,-1,-1)
  9666.                 return (0)
  9667.             end
  9668.         select @objtype = 'column'
  9669.     end
  9670. end
  9671.  
  9672. ------------ index?
  9673. if (lower(@objtype) = 'index' or @objtypeIN is null)
  9674. begin
  9675.     -- find index
  9676.     if (@xtype in ('U','V'))
  9677.         select @indid = indid from sysindexes
  9678.                 where id = @objid and name = @UnqualOldName
  9679.                     AND indid NOT IN (0, 255)
  9680.  
  9681.     -- check for wrong param
  9682.     if ((@indid is not null AND @objtype <> 'index') OR
  9683.         (@indid is null AND @objtype = 'index'))
  9684.     begin
  9685.         raiserror(15248,-1,-1,@objtypeIN)
  9686.         return 1
  9687.     end
  9688.  
  9689.     if (@indid is not null)
  9690.     begin
  9691.         select @objtype = 'index'
  9692.         select @cnstid = id, @xtype = xtype from sysobjects
  9693.             where name = @UnqualOldName AND parent_obj = @objid and xtype in ('PK','UQ')
  9694.     end
  9695. end
  9696.  
  9697. ------------ object?
  9698. if (@objtype = 'object' or @objtypeIN is null)
  9699. begin
  9700.     -- get object id, type
  9701.     select @objid_tmp = object_id(@objname)
  9702.  
  9703.     select @xtype_tmp = xtype, @replinfo = replinfo
  9704.     from sysobjects where id = @objid_tmp
  9705.  
  9706.     -- if object is a system table, a Scalar function, or a table valued function, skip it.
  9707.  
  9708.     -- Cannot rename system table
  9709.     if @xtype_tmp = 'S'
  9710.         select @objid_tmp = NULL
  9711.  
  9712.     -- check for wrong param
  9713.     if ((@objid_tmp is not null AND @objtype <> 'object') OR
  9714.         (@objid_tmp is null AND @objtype = 'object'))
  9715.     begin
  9716.         raiserror(15248,-1,-1,@objtypeIN)
  9717.         return 1
  9718.     end
  9719.  
  9720.     if (@objid_tmp is not null)
  9721.     begin
  9722.  
  9723.         if (@xtype_tmp in ('U'))
  9724.         begin
  9725.             if (@replinfo & @replbits <> 0)
  9726.             begin
  9727.                 raiserror(15051,-1,-1)
  9728.                 return (0)
  9729.             end
  9730.         end
  9731.  
  9732.         select @objtype = 'object', @objid = @objid_tmp, @xtype = @xtype_tmp
  9733.  
  9734.         if (@xtype in ('PK','UQ'))
  9735.             select @parent_obj = parent_obj from sysobjects where id = @objid
  9736.     end
  9737. end
  9738.  
  9739.  
  9740. ------------ type?
  9741. if (@objtype = 'userdatatype' or @objtypeIN is null)
  9742. begin
  9743.     select @xusertype = xusertype from systypes
  9744.         where name = @UnqualOldName and xusertype > 256
  9745.             AND (@QualName1 is null or uid = user_id(@QualName1))
  9746.  
  9747.     -- check for wrong param
  9748.     if ((@xusertype is not null AND @objtype <> 'userdatatype') OR
  9749.         (@xusertype is null AND @objtype = 'userdatatype'))
  9750.     begin
  9751.         raiserror(15248,-1,-1,@objtypeIN)
  9752.         return 1
  9753.     end
  9754.  
  9755.     if (@xusertype IS NOT null)
  9756.         select @objtype = 'userdatatype'
  9757. end
  9758.  
  9759. ---------------------------------------------------------------------
  9760. -------------------  PHASE 30:  More parm edits  --------------------
  9761. ---------------------------------------------------------------------
  9762.  
  9763. -- item type determined?
  9764. if (@objtype IS null)
  9765. begin
  9766.     raiserror(15225,-1,-1,@objname, @CurrentDb, @objtypeIN)
  9767.     return 1
  9768. end
  9769.  
  9770. -- was the original name valid given this type?
  9771. if (@objtype in ('object','userdatatype') AND @CountNumNodes > 3)
  9772. begin
  9773.     raiserror(15225,-1,-1,@objname, @CurrentDb, @objtypeIN)
  9774.     return 1
  9775. end
  9776.  
  9777. -- verify db qualifier is current db
  9778. if (@objtype in ('object','userdatatype'))
  9779.     select @QualName3 = @QualName2
  9780. if (isnull(@QualName3, @CurrentDb) <> @CurrentDb)
  9781. begin
  9782.     raiserror(15333,-1,-1,@QualName3)
  9783.     return 1
  9784. end
  9785.  
  9786. -- get owner id and check permissions
  9787. if (@objtype = 'userdatatype')
  9788.     select @ownerid = uid from systypes where xusertype = @xusertype
  9789. else
  9790.     select @ownerid = ObjectProperty(@objid, 'ownerid')
  9791. if (    (not (1 = is_member('db_owner')))
  9792.     AND (not (1 = is_member('db_ddladmin')))
  9793.     AND (not (1 = is_member(user_name(@ownerid)))) )
  9794. begin
  9795.     raiserror(15247,-1,-1)
  9796.     return 1
  9797. end
  9798.  
  9799. -- check if system object
  9800. if (ObjectProperty(@objid, 'IsMSShipped') = 1 OR
  9801.     ObjectProperty(@objid, 'IsSystemTable') = 1)
  9802. begin
  9803.     raiserror(15001,-1,-1, @objname)
  9804.     return 1
  9805. end
  9806.  
  9807. -- make sure orig no longer shows null
  9808. if @objtypeIN is null
  9809.     select @objtypeIN = @objtype
  9810.  
  9811. -- Check for name clashing with existing name(s)
  9812. if (@newname <> @UnqualOldName)
  9813. begin
  9814.     -- column name clash?
  9815.     if (@objtype = 'column')
  9816.         if (ColumnProperty(@objid, @newname, 'isidentity') is not null)
  9817.             select @UnqualOldName = NULL
  9818.     -- object name clash?
  9819.     if ( (@objtype = 'object' AND @xtype in ('PK','UQ'))
  9820.             OR @objtype = 'index')
  9821.         if exists (select * from sysindexes where id = @objid and name = @newname
  9822.                     and indid not in (0,255))
  9823.             select @UnqualOldName = NULL
  9824.     -- index name clash?
  9825.     if (@objtype = 'object' OR @cnstid IS NOT null)
  9826.         if (object_id(QuoteName(user_name(@ownerid)) +'.'+ QuoteName(@newname)) is not null)
  9827.             select @UnqualOldName = NULL
  9828.     -- type name clash?
  9829.     if (@objtype = 'userdatatype')
  9830.         if exists (select * from systypes where name = @newname)
  9831.             select @UnqualOldName = NULL
  9832.     -- stop on clash
  9833.     if (@UnqualOldName is null)
  9834.     begin
  9835.         raiserror(15335,-1,-1,@newname,@objtypeIN)
  9836.         return 1
  9837.     end
  9838. end
  9839.  
  9840. --------------------------------------------------------------------------
  9841. --------------------  PHASE 32:  Temporay Table Isssue -------------------
  9842. --------------------------------------------------------------------------
  9843. -- Disallow renaming object to or from a temp name (starts with #)
  9844. if (@objtype = 'object' AND
  9845.     (substring(@newname,1,1) = N'#' OR
  9846.     substring(object_name(@objid),1,1) = N'#'))
  9847. begin
  9848.     raiserror(15600,-1,-1, 'sp_rename')
  9849.     return 1
  9850. end
  9851.  
  9852. --------------------------------------------------------------------------
  9853. --------------------  PHASE 34:  Cautionary messages  --------------------
  9854. --------------------------------------------------------------------------
  9855.  
  9856. if @objtype = 'column'
  9857. begin
  9858.     -- Check for Dependencies: No column rename if enforced dependency on column
  9859.     IF EXISTS (SELECT * FROM sysdepends WHERE depid = @objid AND depnumber = @colid AND deptype > 0)
  9860.     begin
  9861.         raiserror(15336,-1,-1, @objname)
  9862.         return 1
  9863.     end
  9864. end
  9865. else if @objtype = 'object'
  9866. begin
  9867.     -- Check for Dependencies: No RENAME or CHANGEOWNER of OBJECT when exists:
  9868.     IF EXISTS (SELECT * FROM sysdepends d WHERE
  9869.         d.depid = @objid        -- A dependency on this object
  9870.         AND d.deptype > 0        -- that is enforced
  9871.         AND @objid <> d.id        -- that isn't a self-reference (self-references don't use object name)
  9872.         AND @objid <>            -- And isn't a reference from a child object (also don't use object name)
  9873.             (SELECT o.parent_obj FROM sysobjects o WHERE o.id = d.id)
  9874.         )
  9875.     begin
  9876.         raiserror(15336,-1,-1, @objname)
  9877.         return 1
  9878.     end
  9879. end
  9880.  
  9881. -- WITH DEFERRED RESOLUTION, SYSDEPENDS IS NOT VERY ACCURATE, SO WE ALSO
  9882. --    RAISE THIS WARNING **UNCONDITIONALLY**, EVEN FOR NON-OBJECT RENAMES
  9883. raiserror(15477,-1,-1)
  9884.  
  9885. -- warn about dependencies...
  9886. if (@objtype = 'objects' and exists (select * from sysdepends where depid = @objid))
  9887.     raiserror(15337,-1,-1)
  9888.  
  9889. --------------------------------------------------------------------------
  9890. ---------------------  PHASE 40:  Update system tables  ------------------
  9891. --------------------------------------------------------------------------
  9892.  
  9893. -- obtain owner-qual object name (for most below)
  9894. select @OwnAndObjName = QuoteName(user_name(@ownerid))+'.'+QuoteName(object_name(@objid))
  9895.  
  9896. -- DO THE UPDATES --
  9897. if (@objtype = 'userdatatype')                        -------- change type name
  9898.     UPDATE systypes set name = @newname where xusertype = @xusertype
  9899. else if (@objtype = 'object')                        -------- change object name
  9900. begin
  9901.     BEGIN  TRANSACTION
  9902.     -- Locks Object and increments schema_ver
  9903.     DBCC LockObjectSchema(@OwnAndObjName)
  9904.     -- update the object name
  9905.     UPDATE sysobjects set name = @newname where id = @objid
  9906.     -- update index-cnst name (no rows changed if not 'PK' or 'UQ')
  9907.     if (@xtype in ('PK','UQ'))
  9908.         UPDATE sysindexes set name = @newname where id = @parent_obj and name = @UnqualOldName
  9909.     -- update base/text index name (no rows changed if not there)
  9910.     else if (@xtype in ('U', 'TF'))
  9911.     begin
  9912.         UPDATE sysindexes set name = @newname where id = @objid AND indid = 0
  9913.         UPDATE sysindexes set name = convert(sysname,'t'+@newname)
  9914.                             where id = @objid AND indid = 255
  9915.     end
  9916.     COMMIT TRANSACTION
  9917. end
  9918. else if (@objtype = 'index')                        -------- change index name
  9919. begin
  9920.     BEGIN  TRANSACTION
  9921.     -- Locks Object and increments schema_ver.
  9922.     DBCC LockObjectSchema(@OwnAndObjName)
  9923.     -- update the index name
  9924.     UPDATE sysindexes set name = @newname where id = @objid and indid = @indid
  9925.     -- change object name if cnst
  9926.     if (@cnstid IS NOT null)
  9927.         UPDATE sysobjects set name = @newname where id = @cnstid
  9928.     COMMIT TRANSACTION
  9929. end
  9930. else if (@objtype = 'column')                        -------- change column name
  9931. begin
  9932.     -- Use DBCC to check for column in use by check-constraint, computed-column, etc
  9933.     -- THIS IS NOT A DOCUMENTED DBCC: DO NOT USE DIRECTLY!
  9934.     DBCC RENAMECOLUMN ( @OwnAndObjName, @UnqualOldName, @newname )
  9935. end
  9936.  
  9937.  
  9938. -------------------------  Finalization  -----------------------
  9939. LABEL_51_AFTERUPDATES:
  9940. Raiserror(15338,-1,-1,@objtypeIN,@newname)
  9941. return 0 -- sp_rename
  9942. go
  9943. /*ANSI_NULLS off for after creation of sp_rename*/
  9944. Set ansi_nulls off
  9945. go
  9946.  
  9947.  
  9948.  
  9949. checkpoint
  9950. go
  9951.  
  9952. raiserror(15339,-1,-1,'sp_resetstatus')
  9953. Go
  9954.  
  9955. CREATE PROCEDURE sp_resetstatus  -- 1995/11/30 14:12 #12092
  9956.        @DBName          sysname
  9957. as
  9958.  
  9959. Set nocount on
  9960.  
  9961. Declare
  9962.        @msg             nvarchar(280)
  9963.       ,@RetCode         integer
  9964.       ,@_error          integer
  9965.       ,@_rowcount       integer
  9966.       ,@int1            integer
  9967.       ,@bitSuspect      integer
  9968.       ,@mode            integer
  9969.       ,@status          integer
  9970.  
  9971. Select
  9972.        @RetCode         = 0  -- 0=no_problem, 1=some_problem
  9973.  
  9974. ---------------------  Restrict to SA  -------------------------
  9975.  
  9976. if (not (is_srvrolemember('sysadmin') = 1))
  9977.    begin
  9978.    RaisError(15247,-1,-1)
  9979.    Select @RetCode = 1
  9980.    GOTO LABEL_86BYEBYE
  9981.    end
  9982.  
  9983.  
  9984. ------------------  Get SuspectBit id value  ------------------
  9985.  
  9986. SELECT       @bitSuspect = min(number)
  9987.       from
  9988.              master..spt_values
  9989.       where  type = 'D  '
  9990.       and    name = 'not recovered'  -- 256, Suspect
  9991.  
  9992. ----------------------  Forbid active txn  ---------------------
  9993.  
  9994. --- (Prior spt_values Sel trips SET implicit_transactions!)
  9995.  
  9996.  
  9997. IF @@trancount > 0
  9998.    begin
  9999.    RaisError(15002,-1,-1,'sp_resetstatus')
  10000.    Select @RetCode = 1
  10001.    GOTO LABEL_86BYEBYE
  10002.    end
  10003.  
  10004.  
  10005. ---------------  Obtain/Report pre-Update values  --------------------
  10006.  
  10007. SELECT
  10008.              @mode   = min(mode)
  10009.             ,@status = min(status)
  10010.       from
  10011.              master..sysdatabases
  10012.       where  name = @DBName
  10013.  
  10014. IF @@error <> 0 OR @status IS Null
  10015.    begin
  10016.    RaisError(15010,-1,-1,@DBName)
  10017.    Select @RetCode = 1
  10018.    GOTO LABEL_86BYEBYE
  10019.    end
  10020.  
  10021.  
  10022. Select @int1 = @status & @bitSuspect
  10023.  
  10024.  
  10025. Raiserror(15052,-1,-1 ,@DBName ,@mode ,@status ,@int1)
  10026.  
  10027. ---------------------  Update sysdatabases row  ---------------------
  10028.  
  10029. BEGIN TRANSACTION
  10030.  
  10031.  
  10032. UPDATE
  10033.              master..sysdatabases
  10034.       set
  10035.              mode    = 0
  10036.             ,status  = status & (~ @bitSuspect)
  10037.       where  name    = @DBName
  10038.       and
  10039.             (mode   <> 0      OR
  10040.              status  & @bitSuspect > 0
  10041.             )
  10042.  
  10043. Select @_error = @@error ,@_rowcount = @@rowcount
  10044.  
  10045.  
  10046. IF @_error <> 0
  10047.    begin
  10048.  
  10049.    ROLLBACK TRANSACTION
  10050.  
  10051.    RaisError(15055,-1,-1)
  10052.    Select @RetCode = 1
  10053.    GOTO LABEL_86BYEBYE
  10054.    end
  10055.  
  10056.  
  10057. COMMIT TRANSACTION
  10058.  
  10059. -------- Report the results
  10060.  
  10061. IF @_rowcount = 0
  10062.    begin
  10063.    Raiserror(15056,-1,-1)
  10064.    end
  10065.  
  10066. ELSE
  10067.    begin
  10068.  
  10069.    Raiserror(15073,-1,-1, @DBName,@bitSuspect)
  10070.  
  10071.    Raiserror(15074,-1,-1)
  10072.  
  10073.    end
  10074.  
  10075.  
  10076. LABEL_86BYEBYE:
  10077.  
  10078. RETURN @RetCode
  10079.  
  10080. Go
  10081.  
  10082.  
  10083. raiserror(15339,-1,-1,'sp_add_file_recover_suspect_db')
  10084. Go
  10085. --
  10086. -- Name: sp_add_file_recover_suspect_db
  10087. -- Purpose: Adds a data or log file to a suspect database and runs
  10088. --         recovery on the database.  This SP should only be used
  10089. --        on databases that have been marked suspect due to
  10090. --        insufficient data (error 1105) or log (error 9002) space.
  10091. -- Note: This SP is not documented.  Only sp_add_data_file_recover_suspect_db
  10092. --    and sp_add_log_file_recover_suspect_db below are documented
  10093. --
  10094. create procedure sp_add_file_recover_suspect_db
  10095.     @dbName     sysname            -- database name
  10096.     ,@fileType    nvarchar(4)        -- "data" or "log"
  10097.     ,@filegroup    nvarchar(260)        -- file group for new file
  10098.     ,@name        nvarchar(260)        -- logical file name
  10099.     ,@filename    nvarchar(260)        -- OS file name
  10100.     ,@size        nvarchar(20)     = NULL    -- initial file size
  10101.     ,@maxsize    nvarchar(20)     = NULL    -- maximum file size
  10102.     ,@filegrowth    nvarchar(20)     = NULL    -- growth increment
  10103.  
  10104. as
  10105.  
  10106. declare @currentStatus int
  10107. declare @suspectBit int
  10108. declare @dboOnlyBit int
  10109. declare @emergencyModeBit int
  10110. declare @returnCode int
  10111. declare @addCmd nvarchar(4000)
  10112. declare @isLog    int
  10113.  
  10114. set nocount on
  10115. select @suspectBit = 0x100
  10116. select @currentStatus = 0
  10117. select @returnCode = 0
  10118.  
  10119. ---------------------  Restrict to SA  -------------------------
  10120.  
  10121. if (not (is_srvrolemember('sysadmin') = 1))
  10122. begin
  10123.    RaisError(15247,-1,-1)
  10124.    Select @returnCode = 1
  10125.    GOTO LABEL_FAILURE
  10126. end
  10127.  
  10128.  
  10129. ------------------  Get Status Bit id values  ------------------
  10130.  
  10131. SELECT       @suspectBit = min(number)
  10132.       from
  10133.              master..spt_values
  10134.       where  type = 'D  '
  10135.       and    name = 'not recovered'  -- 256, Suspect
  10136.  
  10137. SELECT       @dboOnlyBit = min(number)
  10138.       from
  10139.              master..spt_values
  10140.       where  type = 'D  '
  10141.       and    name = 'dbo use only'  -- 2048, dbo only
  10142.  
  10143. SELECT       @emergencyModeBit = min(number)
  10144.       from
  10145.              master..spt_values
  10146.       where  type = 'D  '
  10147.       and    name = 'emergency mode'  -- 32768, dbo only
  10148.  
  10149. --print 'Bit values ' + convert(char(10), @suspectBit) + convert(char(10), @dboOnlyBit) + convert(char(10), @emergencyModeBit)
  10150.  
  10151. -- Determine if this is a data or log file
  10152. --
  10153. IF (UPPER (@fileType) = 'DATA')
  10154. begin
  10155.     select @isLog = 0
  10156. end
  10157. ELSE IF (UPPER (@fileType) = 'LOG')
  10158. begin
  10159.     select @isLog = 1
  10160. end
  10161. ELSE
  10162. begin
  10163.     print 'Must specify data or log file type'
  10164.     select @returnCode = 1
  10165.     GOTO LABEL_FAILURE
  10166. end
  10167.  
  10168.  
  10169.  
  10170. IF @@trancount > 0
  10171. begin
  10172.    RaisError(15002,-1,-1,'sp_add_file_recover_suspect_db')
  10173.    Select @returnCode = 1
  10174.    GOTO LABEL_FAILURE
  10175. end
  10176.  
  10177. -- check that current status includes suspect or emergency-mode
  10178. -- otherwise fail with database does not exist
  10179. --
  10180. select @currentStatus = status from master.dbo.sysdatabases where name = @dbName
  10181.  
  10182. if (@currentStatus is null)
  10183. begin
  10184.     RaisError(15010,-1,-1,@dbName)
  10185.     select @returnCode = 1
  10186.     goto LABEL_FAILURE
  10187. end
  10188.  
  10189. -- set new temporary status to dbo-only and emergency-mode
  10190. --
  10191. BEGIN TRAN
  10192. update master.dbo.sysdatabases set status = (status | @dboOnlyBit | @emergencyModeBit) where name = @dbName
  10193. IF @@error <> 0
  10194. begin
  10195.    ROLLBACK TRANSACTION
  10196.    RaisError(15055,-1,-1)
  10197.    Select @returnCode = 1
  10198.    GOTO LABEL_FAILURE
  10199. end
  10200. COMMIT TRAN
  10201. checkpoint
  10202.  
  10203. -- Build the Alter Database Add File string
  10204. --
  10205. select @addCmd = 'ALTER DATABASE ' + @dbName + ' ADD'
  10206. IF (@isLog = 1)
  10207. begin
  10208.     select @addCmd = @addCmd + ' LOG FILE'
  10209. end
  10210. ELSE
  10211. begin
  10212.     select @addCmd = @addCmd + ' FILE'
  10213. end
  10214. select @addCmd = @addCmd + '(NAME = [' + @name + '], FILENAME = ''' + @filename + ''''
  10215. if (@size IS NOT NULL)
  10216. begin
  10217.     select @addCmd = @addCmd + ', SIZE = ' + @size
  10218. end
  10219. if (@maxsize IS NOT NULL)
  10220. begin
  10221.     select @addCmd = @addCmd + ', MAXSIZE = ' + @maxsize
  10222. end
  10223. if (@filegrowth IS NOT NULL)
  10224. begin
  10225.     select @addCmd = @addCmd + ', FILEGROWTH = ' + @filegrowth
  10226. end
  10227. select @addCmd = @addCmd + ' )'
  10228. if (@filegroup IS NOT NULL)
  10229. begin
  10230.     select @addCmd = @addCmd + ' TO FILEGROUP [' + @filegroup + ']'
  10231. end
  10232. print @addCmd
  10233.  
  10234. EXECUTE (@addCmd)
  10235.  
  10236. -- restore status to what it was before adding the file
  10237. --
  10238. BEGIN TRAN
  10239. update master.dbo.sysdatabases set status = @currentStatus where name = @dbName
  10240. IF @@error <> 0
  10241.    begin
  10242.  
  10243.    ROLLBACK TRANSACTION
  10244.  
  10245.    RaisError(15055,-1,-1)
  10246.    Select @returnCode = 1
  10247.    GOTO LABEL_FAILURE
  10248.    end
  10249. COMMIT TRAN
  10250. checkpoint
  10251.  
  10252. -- Turn off suspect bit if it is on
  10253. --
  10254. if ((@currentStatus & @suspectBit) <> 0)
  10255. begin
  10256.     exec sp_resetstatus @dbName
  10257. end
  10258.  
  10259. -- Run recovery on the database
  10260. --
  10261. select @addCmd = 'dbcc dbrecover (' + @dbName + ')'
  10262. exec (@addCmd)
  10263.  
  10264.  
  10265. GOTO LABEL_SUCCESS
  10266.  
  10267. LABEL_FAILURE:
  10268.     --print 'Failed to add file to and recover the suspect database.'
  10269.     return @returnCode
  10270.  
  10271. LABEL_SUCCESS:
  10272.     --print 'Successfully added file to the database'
  10273.     return @returnCode
  10274. -- sp_add_file_recover_suspect_db
  10275. go
  10276.  
  10277.  
  10278. raiserror(15339,-1,-1,'sp_add_data_file_recover_suspect_db')
  10279. Go
  10280. --
  10281. -- Name: sp_add_data_file_recover_suspect_db
  10282. -- Purpose: Adds a data file to a suspect database and runs
  10283. --         recovery on the database.  This SP should only be used
  10284. --        on databases that have been marked suspect due to
  10285. --        insufficient data (error 1105) or log (error 9002) space.
  10286. --
  10287. create procedure sp_add_data_file_recover_suspect_db
  10288.     @dbName     sysname            -- database name
  10289.     ,@filegroup    nvarchar(260)        -- file group for new file
  10290.     ,@name        nvarchar(260)        -- logical file name
  10291.     ,@filename    nvarchar(260)        -- OS file name
  10292.     ,@size        nvarchar(20)     = NULL    -- initial file size
  10293.     ,@maxsize    nvarchar(20)     = NULL    -- maximum file size
  10294.     ,@filegrowth    nvarchar(20)     = NULL    -- growth increment
  10295. as
  10296. execute sp_add_file_recover_suspect_db @dbName, 'DATA', @filegroup, @name, @filename, @size, @maxsize, @filegrowth
  10297. go
  10298.  
  10299. raiserror(15339,-1,-1,'sp_add_log_file_recover_suspect_db')
  10300. Go
  10301. --
  10302. -- Name: sp_add_log_file_recover_suspect_db
  10303. -- Purpose: Adds a log file to a suspect database and runs
  10304. --         recovery on the database.  This SP should only be used
  10305. --        on databases that have been marked suspect due to
  10306. --        insufficient data (error 1105) or log (error 9002) space.
  10307. --
  10308. create procedure sp_add_log_file_recover_suspect_db
  10309.     @dbName     sysname            -- database name
  10310.     ,@name        nvarchar(260)        -- logical file name
  10311.     ,@filename    nvarchar(260)        -- OS file name
  10312.     ,@size        nvarchar(20)     = NULL    -- initial file size
  10313.     ,@maxsize    nvarchar(20)     = NULL    -- maximum file size
  10314.     ,@filegrowth    nvarchar(20)     = NULL    -- growth increment
  10315. as
  10316. execute sp_add_file_recover_suspect_db @dbName, 'LOG', NULL, @name, @filename, @size, @maxsize, @filegrowth
  10317. go
  10318.  
  10319.  
  10320. raiserror(15339,-1,-1,'sp_spaceused')
  10321. go
  10322. create procedure sp_spaceused --- 1996/08/20 17:01
  10323. @objname nvarchar(776) = null,        -- The object we want size on.
  10324. @updateusage varchar(5) = false        -- Param. for specifying that
  10325.                     -- usage info. should be updated.
  10326. as
  10327.  
  10328. declare @id    int            -- The object id of @objname.
  10329. declare @type    character(2) -- The object type.
  10330. declare    @pages    int            -- Working variable for size calc.
  10331. declare @dbname sysname
  10332. declare @dbsize dec(15,0)
  10333. declare @logsize dec(15)
  10334. declare @bytesperpage    dec(15,0)
  10335. declare @pagesperMB        dec(15,0)
  10336.  
  10337. /*Create temp tables before any DML to ensure dynamic
  10338. **  We need to create a temp table to do the calculation.
  10339. **  reserved: sum(reserved) where indid in (0, 1, 255)
  10340. **  data: sum(dpages) where indid < 2 + sum(used) where indid = 255 (text)
  10341. **  indexp: sum(used) where indid in (0, 1, 255) - data
  10342. **  unused: sum(reserved) - sum(used) where indid in (0, 1, 255)
  10343. */
  10344. create table #spt_space
  10345. (
  10346.     rows        int null,
  10347.     reserved    dec(15) null,
  10348.     data        dec(15) null,
  10349.     indexp        dec(15) null,
  10350.     unused        dec(15) null
  10351. )
  10352.  
  10353. /*
  10354. **  Check to see if user wants usages updated.
  10355. */
  10356.  
  10357. if @updateusage is not null
  10358.     begin
  10359.         select @updateusage=lower(@updateusage)
  10360.  
  10361.         if @updateusage not in ('true','false')
  10362.             begin
  10363.                 raiserror(15143,-1,-1,@updateusage)
  10364.                 return(1)
  10365.             end
  10366.     end
  10367. /*
  10368. **  Check to see that the objname is local.
  10369. */
  10370. if @objname IS NOT NULL
  10371. begin
  10372.  
  10373.     select @dbname = parsename(@objname, 3)
  10374.  
  10375.     if @dbname is not null and @dbname <> db_name()
  10376.         begin
  10377.             raiserror(15250,-1,-1)
  10378.             return (1)
  10379.         end
  10380.  
  10381.     if @dbname is null
  10382.         select @dbname = db_name()
  10383.  
  10384.     /*
  10385.     **  Try to find the object.
  10386.     */
  10387.     select @id = null
  10388.     select @id = id, @type = xtype
  10389.         from sysobjects
  10390.             where id = object_id(@objname)
  10391.  
  10392.     /*
  10393.     **  Does the object exist?
  10394.     */
  10395.     if @id is null
  10396.         begin
  10397.             raiserror(15009,-1,-1,@objname,@dbname)
  10398.             return (1)
  10399.         end
  10400.  
  10401.  
  10402.     if not exists (select * from sysindexes
  10403.                 where @id = id and indid < 2)
  10404.  
  10405.         if      @type in ('P ','D ','R ','TR','C ','RF') --data stored in sysprocedures
  10406.                 begin
  10407.                     raiserror(15234,-1,-1)
  10408.                     return (1)
  10409.                 end
  10410.         else if @type = 'V ' -- View => no physical data storage.
  10411.                 begin
  10412.                     raiserror(15235,-1,-1)
  10413.                     return (1)
  10414.                 end
  10415.         else if @type in ('PK','UQ') -- no physical data storage. --?!?! too many similar messages
  10416.                 begin
  10417.                     raiserror(15064,-1,-1)
  10418.                     return (1)
  10419.                 end
  10420.         else if @type = 'F ' -- FK => no physical data storage.
  10421.                 begin
  10422.                     raiserror(15275,-1,-1)
  10423.                     return (1)
  10424.                 end
  10425. end
  10426.  
  10427. /*
  10428. **  Update usages if user specified to do so.
  10429. */
  10430.  
  10431. if @updateusage = 'true'
  10432.     begin
  10433.         if @objname is null
  10434.             dbcc updateusage(0) with no_infomsgs
  10435.         else
  10436.             dbcc updateusage(0,@objname) with no_infomsgs
  10437.         print ' '
  10438.     end
  10439.  
  10440.  
  10441. set nocount on
  10442.  
  10443. /*
  10444. **  If @id is null, then we want summary data.
  10445. */
  10446. /*    Space used calculated in the following way
  10447. **    @dbsize = Pages used
  10448. **    @bytesperpage = d.low (where d = master.dbo.spt_values) is
  10449. **    the # of bytes per page when d.type = 'E' and
  10450. **    d.number = 1.
  10451. **    Size = @dbsize * d.low / (1048576 (OR 1 MB))
  10452. */
  10453. if @id is null
  10454. begin
  10455.     select @dbsize = sum(convert(dec(15),size))
  10456.         from dbo.sysfiles
  10457.         where (status & 64 = 0)
  10458.  
  10459.     select @logsize = sum(convert(dec(15),size))
  10460.         from dbo.sysfiles
  10461.         where (status & 64 <> 0)
  10462.  
  10463.     select @bytesperpage = low
  10464.         from master.dbo.spt_values
  10465.         where number = 1
  10466.             and type = 'E'
  10467.     select @pagesperMB = 1048576 / @bytesperpage
  10468.  
  10469.     select  database_name = db_name(),
  10470.         database_size =
  10471.             ltrim(str((@dbsize + @logsize) / @pagesperMB,15,2) + ' MB'),
  10472.         'unallocated space' =
  10473.             ltrim(str((@dbsize -
  10474.                 (select sum(convert(dec(15),reserved))
  10475.                     from sysindexes
  10476.                         where indid in (0, 1, 255)
  10477.                 )) / @pagesperMB,15,2)+ ' MB')
  10478.  
  10479.     print ' '
  10480.     /*
  10481.     **  Now calculate the summary data.
  10482.     **  reserved: sum(reserved) where indid in (0, 1, 255)
  10483.     */
  10484.     insert into #spt_space (reserved)
  10485.         select sum(convert(dec(15),reserved))
  10486.             from sysindexes
  10487.                 where indid in (0, 1, 255)
  10488.  
  10489.     /*
  10490.     ** data: sum(dpages) where indid < 2
  10491.     **    + sum(used) where indid = 255 (text)
  10492.     */
  10493.     select @pages = sum(convert(dec(15),dpages))
  10494.             from sysindexes
  10495.                 where indid < 2
  10496.     select @pages = @pages + isnull(sum(convert(dec(15),used)), 0)
  10497.         from sysindexes
  10498.             where indid = 255
  10499.     update #spt_space
  10500.         set data = @pages
  10501.  
  10502.  
  10503.     /* index: sum(used) where indid in (0, 1, 255) - data */
  10504.     update #spt_space
  10505.         set indexp = (select sum(convert(dec(15),used))
  10506.                 from sysindexes
  10507.                     where indid in (0, 1, 255))
  10508.                 - data
  10509.  
  10510.     /* unused: sum(reserved) - sum(used) where indid in (0, 1, 255) */
  10511.     update #spt_space
  10512.         set unused = reserved
  10513.                 - (select sum(convert(dec(15),used))
  10514.                     from sysindexes
  10515.                         where indid in (0, 1, 255))
  10516.  
  10517.     select reserved = ltrim(str(reserved * d.low / 1024.,15,0) +
  10518.                 ' ' + 'KB'),
  10519.         data = ltrim(str(data * d.low / 1024.,15,0) +
  10520.                 ' ' + 'KB'),
  10521.         index_size = ltrim(str(indexp * d.low / 1024.,15,0) +
  10522.                 ' ' + 'KB'),
  10523.         unused = ltrim(str(unused * d.low / 1024.,15,0) +
  10524.                 ' ' + 'KB')
  10525.         from #spt_space, master.dbo.spt_values d
  10526.         where d.number = 1
  10527.             and d.type = 'E'
  10528. end
  10529.  
  10530. /*
  10531. **  We want a particular object.
  10532. */
  10533. else
  10534. begin
  10535.     /*
  10536.     **  Now calculate the summary data.
  10537.     **  reserved: sum(reserved) where indid in (0, 1, 255)
  10538.     */
  10539.     insert into #spt_space (reserved)
  10540.         select sum(reserved)
  10541.             from sysindexes
  10542.                 where indid in (0, 1, 255)
  10543.                     and id = @id
  10544.  
  10545.     /*
  10546.     ** data: sum(dpages) where indid < 2
  10547.     **    + sum(used) where indid = 255 (text)
  10548.     */
  10549.     select @pages = sum(dpages)
  10550.             from sysindexes
  10551.                 where indid < 2
  10552.                     and id = @id
  10553.     select @pages = @pages + isnull(sum(used), 0)
  10554.         from sysindexes
  10555.             where indid = 255
  10556.                 and id = @id
  10557.     update #spt_space
  10558.         set data = @pages
  10559.  
  10560.  
  10561.     /* index: sum(used) where indid in (0, 1, 255) - data */
  10562.     update #spt_space
  10563.         set indexp = (select sum(used)
  10564.                 from sysindexes
  10565.                     where indid in (0, 1, 255)
  10566.                         and id = @id)
  10567.                 - data
  10568.  
  10569.     /* unused: sum(reserved) - sum(used) where indid in (0, 1, 255) */
  10570.     update #spt_space
  10571.         set unused = reserved
  10572.                 - (select sum(used)
  10573.                     from sysindexes
  10574.                         where indid in (0, 1, 255)
  10575.                             and id = @id)
  10576.     update #spt_space
  10577.         set rows = i.rows
  10578.             from sysindexes i
  10579.                 where i.indid < 2
  10580.                     and i.id = @id
  10581.  
  10582.     select name = object_name(@id),
  10583.         rows = convert(char(11), rows),
  10584.         reserved = ltrim(str(reserved * d.low / 1024.,15,0) +
  10585.                 ' ' + 'KB'),
  10586.         data = ltrim(str(data * d.low / 1024.,15,0) +
  10587.                 ' ' + 'KB'),
  10588.         index_size = ltrim(str(indexp * d.low / 1024.,15,0) +
  10589.                 ' ' + 'KB'),
  10590.         unused = ltrim(str(unused * d.low / 1024.,15,0) +
  10591.                 ' ' + 'KB')
  10592.     from #spt_space, master.dbo.spt_values d
  10593.         where d.number = 1
  10594.             and d.type = 'E'
  10595. end
  10596.  
  10597. return (0) -- sp_spaceused
  10598. go
  10599.  
  10600. checkpoint
  10601. go
  10602.  
  10603. raiserror(15339,-1,-1,'sp_sqlexec')
  10604.  
  10605. -- sp_sqlexec should not be allowed to update system catalog
  10606. exec sp_configure 'allow updates',0
  10607. reconfigure with override
  10608. go
  10609.  
  10610. create procedure sp_sqlexec --- 1996/04/08 00:00
  10611.     @p1 text
  10612. as
  10613. exec(@p1)
  10614. go
  10615.  
  10616. exec sp_configure 'allow updates',1
  10617. reconfigure with override
  10618.  
  10619. go
  10620.  
  10621.  
  10622. raiserror(15339,-1,-1,'sp_unbindefault')
  10623. go
  10624. create procedure sp_unbindefault --- 1996/08/13 13:34
  10625. @objname nvarchar(776),         /* table/column or datatype name */
  10626. @futureonly varchar(15) = NULL   /* flag to indicate extent of binding */
  10627. as
  10628.  
  10629. declare @futurevalue varchar(15) /* the value of @futureonly that causes
  10630.                ** the binding to be limited */
  10631.  
  10632. declare
  10633.     @vc1            nvarchar(517)
  10634. declare
  10635.     @tab_id            integer
  10636.     ,@cur_tab_id    integer
  10637.     ,@colid            integer
  10638.     ,@cdefault        integer
  10639.     ,@olddefault    integer
  10640.     ,@xusertype        smallint
  10641.  
  10642.     ,@UnqualObj        sysname
  10643.     ,@QualObj1        sysname
  10644.     ,@QualObj2        sysname
  10645.     ,@QualObj3        sysname
  10646.  
  10647. set cursor_close_on_commit    off
  10648. select @futurevalue = 'futureonly'  /* initialize @futurevalue */
  10649.  
  10650. /*
  10651. **  When a default or rule is bound to a user-defined datatype, it is also
  10652. **  bound, by default, to any columns of the user datatype that are currently
  10653. **  using the existing default or rule as their default or rule.  This default
  10654. **  action may be overridden by setting @futureonly = @futurevalue when the
  10655. **  procedure is invoked.  In this case existing columns with the user
  10656. **  datatype won't have their existing default or rule changed.
  10657. */
  10658.  
  10659. -- get name parts --
  10660. select @UnqualObj = parsename(@objname, 1),
  10661.         @QualObj1 = parsename(@objname, 2),
  10662.         @QualObj2 = parsename(@objname, 3),
  10663.         @QualObj3 = parsename(@objname, 4)
  10664.  
  10665. IF (@UnqualObj is NULL OR @QualObj3 is not null)
  10666.    begin
  10667.    raiserror(15253,-1,-1,@objname)
  10668.    return (1)
  10669.    end
  10670.  
  10671.  
  10672. ------------------  Verify database.
  10673.  
  10674. if (@QualObj2 is not null and @QualObj1 is null)
  10675.     begin
  10676.         raiserror(15084,-1,-1)
  10677.         return (1)
  10678.     end
  10679.  
  10680. /*
  10681. **  If @objname is of the form tab.col then we are unbinding a column.
  10682. **  Otherwise its a datatype.  In the column case, we need to extract
  10683. **  and verify the table and column names and make sure the user owns
  10684. **  the table that is getting the default unbound.
  10685. */
  10686. if @QualObj1 is not null
  10687. begin
  10688.     if (@QualObj2 is not null)
  10689.         select @vc1 = QuoteName(@QualObj2) + '.' + QuoteName(@QualObj1)
  10690.     else
  10691.         select @vc1 = QuoteName(@QualObj1)
  10692.  
  10693.    /*
  10694.    **  Find it and unbind it.
  10695.    */
  10696.    select @tab_id = c.id, @colid = c.colid, @cdefault = c.cdefault
  10697.    from syscolumns c, sysobjects o
  10698.       where c.id = o.id
  10699.          and c.name = @UnqualObj
  10700.          and o.id = object_id(@vc1,'local')
  10701.          and o.xtype = N'U '
  10702.  
  10703.     if @tab_id is null
  10704.     begin
  10705.          raiserror(15104,-1,-1,@QualObj1,@UnqualObj)
  10706.          return(1)
  10707.     end
  10708.  
  10709.     if @cdefault = 0
  10710.     begin
  10711.         raiserror(15236,-1,-1,@objname)
  10712.         return(1)
  10713.     end
  10714.  
  10715.     if exists
  10716.     (select    *
  10717.         from    sysobjects o
  10718.         where    @cdefault    = o.id
  10719.             and    @tab_id        = o.parent_obj)
  10720.         begin
  10721.             raiserror(15049,-1,-1, @objname)
  10722.             return (1)
  10723.         end
  10724.  
  10725.     BEGIN TRANSACTION txn_unbindefault_1
  10726.  
  10727.          /*
  10728.          **  Since binding a default is a schema change,
  10729.          **  update schema count
  10730.          **  for the object in the sysobjects table.
  10731.          */
  10732.         dbcc LockObjectSchema(@vc1) --- Undocu. Locks out other schema changes until commit, and increments sysobjects.schema_ver.
  10733.  
  10734.         update syscolumns set cdefault = 0
  10735.             from syscolumns where id = @tab_id and colid = @colid
  10736.  
  10737.     COMMIT TRANSACTION txn_bindefault_1
  10738.  
  10739.     raiserror(15519,-1,-1)
  10740.     return (0)
  10741.  
  10742. end
  10743.  
  10744. else
  10745.  
  10746. begin
  10747.    /*
  10748.    **  We're unbinding to a user type.  In this case, the @objname
  10749.    **  is really the name of the user datatype.
  10750.    **  When we unbind to a user type, any existing columns get changed
  10751.    **  to the new binding unless their current binding is not equal
  10752.    **  to the current binding for the usertype or if they set the
  10753.    **  @futureonly parameter to @futurevalue.
  10754.    */
  10755.  
  10756.    /*
  10757.    **  Get the current default for the datatype.
  10758.    */
  10759.    select @olddefault = tdefault, @xusertype = xusertype
  10760.         from systypes where name = @UnqualObj and xusertype > 256
  10761.         AND (is_member('db_owner') = 1 OR is_member('db_ddladmin') = 1 OR is_member(user_name(uid))=1)
  10762.  
  10763.    if @olddefault is null
  10764.       begin
  10765.          raiserror(15036,-1,-1,@UnqualObj)
  10766.          return (1)
  10767.       end
  10768.  
  10769.    if @olddefault = 0
  10770.       begin
  10771.          raiserror(15237,-1,-1,@UnqualObj)
  10772.          return (1)
  10773.       end
  10774.  
  10775.    update systypes set tdefault = 0
  10776.       from systypes
  10777.       where xusertype = @xusertype
  10778.  
  10779.    raiserror(15520,-1,-1)
  10780.  
  10781.    /*
  10782.    **  Now see if there are any columns with the usertype that
  10783.    **  need the new binding.
  10784.    */
  10785.    select @futureonly = lower(@futureonly)
  10786.    if isnull(@futureonly, ' ') <> @futurevalue
  10787.    begin
  10788.         declare ms_crs_unbindefault_1 cursor local static for
  10789.             select
  10790.             distinct
  10791.                  c.id
  10792.                 ,c.colid
  10793.             from     syscolumns c JOIN sysobjects o ON c.id = o.id AND o.xtype = N'U '
  10794.                  where  c.xusertype = @xusertype
  10795.                     and c.cdefault = @olddefault
  10796.             order by c.id
  10797.                     for read only
  10798.  
  10799.         open ms_crs_unbindefault_1
  10800.  
  10801.         fetch next from ms_crs_unbindefault_1 into
  10802.             @tab_id
  10803.             ,@colid
  10804.  
  10805.         BEGIN TRANSACTION txn_unbindefault_2
  10806.  
  10807.             while @@fetch_status = 0
  10808.             begin
  10809.  
  10810.                 select @vc1 = quotename(user_name(OBJECTPROPERTY(@tab_id,'OwnerId'))) + '.'
  10811.                 + quotename(object_name(@tab_id))
  10812.  
  10813.                 dbcc LockObjectSchema(@vc1) --- Undocu. Locks out other schema changes until commit, and increments sysobjects.schema_ver.
  10814.  
  10815.                 select @cur_tab_id = @tab_id
  10816.  
  10817.                 while @cur_tab_id = @tab_id and @@fetch_status = 0
  10818.                 begin
  10819.                       update syscolumns set cdefault = 0
  10820.                     from syscolumns
  10821.                     where id = @tab_id and colid = @colid
  10822.  
  10823.                     fetch next from ms_crs_unbindefault_1 into
  10824.                         @tab_id
  10825.                         ,@colid
  10826.                 end
  10827.             end --loop 3      /*
  10828.  
  10829.         COMMIT TRANSACTION txn_unbindefault_2
  10830.  
  10831.         deallocate ms_crs_unbindefault_1
  10832.  
  10833.         raiserror(15521,-1,-1)
  10834.     end
  10835. end
  10836.  
  10837. return (0) -- sp_unbindefault
  10838. go
  10839.  
  10840. raiserror(15339,-1,-1,'sp_unbindrule')
  10841. go
  10842. create procedure sp_unbindrule --- 1996/08/13 13:33
  10843. @objname nvarchar(776),         /* table/column or datatype name */
  10844. @futureonly varchar(15) = NULL      /* flag to indicate extent of binding */
  10845. as
  10846.  
  10847. declare @oldrule int /* current rule for type */
  10848. declare @tabname sysname     /* name of table */
  10849. declare @colname sysname     /* name of column */
  10850. declare @futurevalue varchar(15) /* the value of @futureonly that causes
  10851.                            ** the binding to be limited */
  10852.  
  10853. declare
  10854.     @vc1            nvarchar(517)
  10855. declare
  10856.      @obj_id        integer
  10857.     ,@cur_tab_id    integer
  10858.     ,@colid            integer
  10859.     ,@domain        integer
  10860.     ,@xusertype        smallint
  10861.  
  10862.     ,@owner_name    sysname
  10863.     ,@obj_name        sysname
  10864.  
  10865.     ,@UnqualObj            sysname
  10866.     ,@QualObj1            sysname
  10867.     ,@QualObj2            sysname
  10868.     ,@QualObj3            sysname
  10869.  
  10870. set cursor_close_on_commit    off
  10871.  
  10872. select @futurevalue = 'futureonly'  /* initialize @futurevalue */
  10873.  
  10874. /*
  10875. **  When a default or rule is bound to a user-defined datatype, it is also
  10876. **  bound, by default, to any columns of the user datatype that are currently
  10877. **  using the existing default or rule as their default or rule.  This default
  10878. **  action may be overridden by setting @futureonly = @futurevalue when the
  10879. **  procedure is invoked.  In this case existing columns with the user
  10880. **  datatype won't have their existing default or rule changed.
  10881. */
  10882.  
  10883. -- get name parts --
  10884. select @UnqualObj = parsename(@objname, 1),
  10885.         @QualObj1 = parsename(@objname, 2),
  10886.         @QualObj2 = parsename(@objname, 3),
  10887.         @QualObj3 = parsename(@objname, 4)
  10888.  
  10889. IF (@UnqualObj is NULL OR @QualObj3 is not null)
  10890.    begin
  10891.    raiserror(15253,-1,-1,@objname)
  10892.    return (1)
  10893.    end
  10894.  
  10895.  
  10896. ------------------  Verify database.
  10897.  
  10898. if (@QualObj2 is not null and @QualObj1 is null)
  10899.     begin
  10900.         raiserror(15084,-1,-1)
  10901.         return (1)
  10902.     end
  10903.  
  10904. /*
  10905. **  If @objname is of the form tab.col then we are unbinding a column.
  10906. **  Otherwise its a datatype.  In the column case, we need to extract
  10907. **  and verify the table and column names and make sure the user owns
  10908. **  the table that is getting the default unbound.
  10909. */
  10910. if @QualObj1 is not null
  10911. begin
  10912.     if (@QualObj2 is not null)
  10913.         select @vc1 = QuoteName(@QualObj2) + '.' + QuoteName(@QualObj1)
  10914.     else
  10915.         select @vc1 = QuoteName(@QualObj1)
  10916.  
  10917.     select    @obj_id = c.id,    @colid = c.colid,    @domain = c.domain
  10918.         from syscolumns c, sysobjects o
  10919.     where c.id = o.id
  10920.     and c.name = @UnqualObj
  10921.     and o.id = object_id(@vc1,'local')
  10922.     and o.xtype = N'U '
  10923.  
  10924.     if @obj_id is null
  10925.     begin
  10926.         raiserror(15104,-1,-1,@QualObj1,@UnqualObj)
  10927.         return (1)
  10928.     end
  10929.  
  10930.     if @domain = 0
  10931.     begin
  10932.         raiserror(15238,-1,-1,@objname)
  10933.         return (1)
  10934.     end
  10935.  
  10936.     BEGIN TRANSACTION txn_unbindrule_1
  10937.  
  10938.         /*
  10939.         **  Update schema count
  10940.         **  for the object in the sysobjects table.
  10941.         */
  10942.  
  10943.         dbcc LockObjectSchema(@vc1) -- Locks Object and increments schema_ver.
  10944.  
  10945.         update syscolumns set domain = 0
  10946.             from syscolumns c where id = @obj_id and colid = @colid
  10947.  
  10948.     COMMIT TRANSACTION txn_unbindrule_1
  10949.  
  10950.     raiserror(15522,-1,-1)
  10951.  
  10952. end
  10953. else
  10954. begin
  10955.  
  10956.     select @oldrule = domain, @xusertype = xusertype
  10957.         from systypes where name = @UnqualObj and xusertype > 256
  10958.         AND (is_member('db_owner') = 1 OR is_member('db_ddladmin') = 1 OR is_member(user_name(uid))=1)
  10959.  
  10960.     if @xusertype is null
  10961.     begin
  10962.         raiserror(15036,-1,-1,@UnqualObj)
  10963.         return (1)
  10964.     end
  10965.  
  10966.     if @oldrule = 0
  10967.     begin
  10968.         raiserror(15239,-1,-1,@UnqualObj)
  10969.         return (1)
  10970.     end
  10971.  
  10972.     update systypes set domain = 0
  10973.     from systypes
  10974.     where xusertype = @xusertype
  10975.  
  10976.     raiserror(15523,-1,-1)
  10977.  
  10978.     select @futureonly = lower(@futureonly)
  10979.     if isnull(@futureonly, ' ') <> @futurevalue
  10980.     begin
  10981.  
  10982.         declare ms_crs_unbindrule_1 cursor local static for
  10983.         select
  10984.             distinct
  10985.              o.id
  10986.             ,user_name(o.uid)
  10987.             ,o.name
  10988.             ,c.colid
  10989.         from    syscolumns c
  10990.             ,sysobjects o
  10991.          where o.id = c.id and o.xtype = N'U '
  10992.             and c.xusertype = @xusertype
  10993.             and c.domain = @oldrule
  10994.         order by o.id
  10995.             for read only
  10996.  
  10997.         open ms_crs_unbindrule_1
  10998.  
  10999.  
  11000.         BEGIN TRANSACTION txn_unbindrule_2
  11001.  
  11002.             fetch next from ms_crs_unbindrule_1 into
  11003.             @obj_id
  11004.             ,@owner_name
  11005.             ,@obj_name
  11006.             ,@colid
  11007.  
  11008.             while @@fetch_status = 0
  11009.             begin
  11010.  
  11011.                 select @vc1 = quotename(@owner_name) + '.' + quotename(@obj_name)
  11012.  
  11013.                 dbcc LockObjectSchema(@vc1) --- Undocu. Locks out other schema changes until commit, and increments sysobjects.schema_ver.
  11014.  
  11015.                 select @cur_tab_id = @obj_id
  11016.  
  11017.                 while @cur_tab_id = @obj_id and @@fetch_status = 0
  11018.                 begin
  11019.                       update syscolumns set domain = 0
  11020.                     from syscolumns
  11021.                     where id = @obj_id and colid = @colid
  11022.  
  11023.                     fetch next from ms_crs_unbindrule_1 into
  11024.                     @obj_id
  11025.                     ,@owner_name
  11026.                     ,@obj_name
  11027.                     ,@colid
  11028.                 end
  11029.             end
  11030.  
  11031.         COMMIT TRANSACTION txn_unbindrule_2
  11032.         deallocate ms_crs_unbindrule_1
  11033.         raiserror(15524,-1,-1)
  11034.  
  11035.     end
  11036. end
  11037.  
  11038. return (0)    --sp_unbindrule
  11039. go
  11040.  
  11041.  
  11042. checkpoint
  11043. go
  11044.  
  11045. --
  11046. raiserror(15339,-1,-1,'sp_who')
  11047. go
  11048. create procedure sp_who  --- 1995/11/28 15:48
  11049.        @loginame sysname = NULL --or 'active'
  11050. as
  11051.  
  11052. declare     @spidlow    int,
  11053.          @spidhigh    int,
  11054.          @spid        int,
  11055.          @sid        varbinary(85)
  11056.  
  11057. select     @spidlow    =     0
  11058.         ,@spidhigh    = 32767
  11059.  
  11060.  
  11061. if (    @loginame is not NULL
  11062.    AND    upper(@loginame) = 'ACTIVE'
  11063.    )
  11064.     begin
  11065.  
  11066.     select spid , ecid, status
  11067.               ,loginame=rtrim(loginame)
  11068.           ,hostname ,blk=convert(char(5),blocked)
  11069.           ,dbname = case
  11070.                         when dbid = 0 then null
  11071.                         when dbid <> 0 then db_name(dbid)
  11072.                     end
  11073.           ,cmd
  11074.     from  master.dbo.sysprocesses
  11075.     where spid >= @spidlow and spid <= @spidhigh AND
  11076.           upper(cmd) <> 'AWAITING COMMAND'
  11077.  
  11078.     return (0)
  11079.     end
  11080.  
  11081. if (@loginame is not NULL
  11082.    AND    upper(@loginame) <> 'ACTIVE'
  11083.    )
  11084. begin
  11085.     if (@loginame like '[0-9]%')    -- is a spid.
  11086.     begin
  11087.         select @spid = convert(int, @loginame)
  11088.         select spid, ecid, status,
  11089.                loginame=rtrim(loginame),
  11090.                hostname,blk = convert(char(5),blocked),
  11091.                dbname = case
  11092.                             when dbid = 0 then null
  11093.                             when dbid <> 0 then db_name(dbid)
  11094.                         end
  11095.               ,cmd
  11096.         from  master.dbo.sysprocesses
  11097.         where spid = @spid
  11098.     end
  11099.     else
  11100.     begin
  11101.         select @sid = suser_sid(@loginame)
  11102.         if (@sid is null)
  11103.         begin
  11104.             raiserror(15007,-1,-1,@loginame)
  11105.             return (1)
  11106.         end
  11107.         select spid, ecid, status,
  11108.                loginame=rtrim(loginame),
  11109.                hostname ,blk=convert(char(5),blocked),
  11110.                dbname = case
  11111.                             when dbid = 0 then null
  11112.                             when dbid <> 0 then db_name(dbid)
  11113.                         end
  11114.                ,cmd
  11115.         from  master.dbo.sysprocesses
  11116.         where sid = @sid
  11117.     end
  11118.     return (0)
  11119. end
  11120.  
  11121.  
  11122. /* loginame arg is null */
  11123. select spid,
  11124.        ecid,
  11125.        status,
  11126.        loginame=rtrim(loginame),
  11127.        hostname,
  11128.        blk=convert(char(5),blocked),
  11129.        dbname = case
  11130.                     when dbid = 0 then null
  11131.                     when dbid <> 0 then db_name(dbid)
  11132.                 end
  11133.        ,cmd
  11134. from  master.dbo.sysprocesses
  11135. where spid >= @spidlow and spid <= @spidhigh
  11136.  
  11137.  
  11138. return (0) -- sp_who
  11139. go
  11140.  
  11141.  
  11142.  
  11143. raiserror(15339,-1,-1,'sp_who2')
  11144. go
  11145. CREATE PROCEDURE sp_who2  --- 1995/11/03 10:16
  11146.     @loginame     sysname = NULL
  11147. as
  11148.  
  11149. set nocount on
  11150.  
  11151. declare
  11152.     @retcode         int
  11153.  
  11154. declare
  11155.     @sidlow         varbinary(85)
  11156.    ,@sidhigh        varbinary(85)
  11157.    ,@sid1           varbinary(85)
  11158.    ,@spidlow         int
  11159.    ,@spidhigh        int
  11160.  
  11161. declare
  11162.     @charMaxLenLoginName      varchar(6)
  11163.    ,@charMaxLenDBName         varchar(6)
  11164.    ,@charMaxLenCPUTime        varchar(10)
  11165.    ,@charMaxLenDiskIO         varchar(10)
  11166.    ,@charMaxLenHostName       varchar(10)
  11167.    ,@charMaxLenProgramName    varchar(10)
  11168.    ,@charMaxLenLastBatch      varchar(10)
  11169.    ,@charMaxLenCommand        varchar(10)
  11170.  
  11171. declare
  11172.     @charsidlow              varchar(85)
  11173.    ,@charsidhigh             varchar(85)
  11174.    ,@charspidlow              varchar(11)
  11175.    ,@charspidhigh             varchar(11)
  11176.  
  11177. --------
  11178.  
  11179. select
  11180.     @retcode         = 0      -- 0=good ,1=bad.
  11181.  
  11182. --------defaults
  11183. select @sidlow = convert(varbinary(85), (replicate(char(0), 85)))
  11184. select @sidhigh = convert(varbinary(85), (replicate(char(1), 85)))
  11185.  
  11186. select
  11187.     @spidlow         = 0
  11188.    ,@spidhigh        = 32767
  11189.  
  11190. --------------------------------------------------------------
  11191. IF (@loginame IS     NULL)  --Simple default to all LoginNames.
  11192.       GOTO LABEL_17PARM1EDITED
  11193.  
  11194. --------
  11195.  
  11196. -- select @sid1 = suser_sid(@loginame)
  11197. select @sid1 = null
  11198. if exists(select * from master.dbo.syslogins where loginname = @loginame)
  11199.     select @sid1 = sid from master.dbo.syslogins where loginname = @loginame
  11200.  
  11201. IF (@sid1 IS NOT NULL)  --Parm is a recognized login name.
  11202.    begin
  11203.    select @sidlow  = suser_sid(@loginame)
  11204.          ,@sidhigh = suser_sid(@loginame)
  11205.    GOTO LABEL_17PARM1EDITED
  11206.    end
  11207.  
  11208. --------
  11209.  
  11210. IF (lower(@loginame) IN ('active'))  --Special action, not sleeping.
  11211.    begin
  11212.    select @loginame = lower(@loginame)
  11213.    GOTO LABEL_17PARM1EDITED
  11214.    end
  11215.  
  11216. --------
  11217.  
  11218. IF (patindex ('%[^0-9]%' , isnull(@loginame,'z')) = 0)  --Is a number.
  11219.    begin
  11220.    select
  11221.              @spidlow   = convert(int, @loginame)
  11222.             ,@spidhigh  = convert(int, @loginame)
  11223.    GOTO LABEL_17PARM1EDITED
  11224.    end
  11225.  
  11226. --------
  11227.  
  11228. RaisError(15007,-1,-1,@loginame)
  11229. select @retcode = 1
  11230. GOTO LABEL_86RETURN
  11231.  
  11232.  
  11233. LABEL_17PARM1EDITED:
  11234.  
  11235.  
  11236. --------------------  Capture consistent sysprocesses.  -------------------
  11237.  
  11238. SELECT
  11239.  
  11240.   spid
  11241.  ,status
  11242.  ,sid
  11243.  ,hostname
  11244.  ,program_name
  11245.  ,cmd
  11246.  ,cpu
  11247.  ,physical_io
  11248.  ,blocked
  11249.  ,dbid
  11250.  ,convert(sysname, rtrim(loginame))
  11251.         as loginname
  11252.  ,spid as 'spid_sort'
  11253.  
  11254.  ,  substring( convert(varchar,last_batch,111) ,6  ,5 ) + ' '
  11255.   + substring( convert(varchar,last_batch,113) ,13 ,8 )
  11256.        as 'last_batch_char'
  11257.  
  11258.       INTO    #tb1_sysprocesses
  11259.       from master.dbo.sysprocesses   (nolock)
  11260.  
  11261.  
  11262.  
  11263. --------Screen out any rows?
  11264.  
  11265. IF (@loginame IN ('active'))
  11266.    DELETE #tb1_sysprocesses
  11267.          where   lower(status)  = 'sleeping'
  11268.          and     upper(cmd)    IN (
  11269.                      'AWAITING COMMAND'
  11270.                     ,'MIRROR HANDLER'
  11271.                     ,'LAZY WRITER'
  11272.                     ,'CHECKPOINT SLEEP'
  11273.                     ,'RA MANAGER'
  11274.                                   )
  11275.  
  11276.          and     blocked       = 0
  11277.  
  11278.  
  11279.  
  11280. --------Prepare to dynamically optimize column widths.
  11281.  
  11282.  
  11283. Select
  11284.     @charsidlow     = convert(varchar(85),@sidlow)
  11285.    ,@charsidhigh    = convert(varchar(85),@sidhigh)
  11286.    ,@charspidlow     = convert(varchar,@spidlow)
  11287.    ,@charspidhigh    = convert(varchar,@spidhigh)
  11288.  
  11289.  
  11290.  
  11291. SELECT
  11292.              @charMaxLenLoginName =
  11293.                   convert( varchar
  11294.                           ,isnull( max( datalength(loginname)) ,5)
  11295.                          )
  11296.  
  11297.             ,@charMaxLenDBName    =
  11298.                   convert( varchar
  11299.                           ,isnull( max( datalength( rtrim(convert(varchar(128),db_name(dbid))))) ,6)
  11300.                          )
  11301.  
  11302.             ,@charMaxLenCPUTime   =
  11303.                   convert( varchar
  11304.                           ,isnull( max( datalength( rtrim(convert(varchar(128),cpu)))) ,7)
  11305.                          )
  11306.  
  11307.             ,@charMaxLenDiskIO    =
  11308.                   convert( varchar
  11309.                           ,isnull( max( datalength( rtrim(convert(varchar(128),physical_io)))) ,6)
  11310.                          )
  11311.  
  11312.             ,@charMaxLenCommand  =
  11313.                   convert( varchar
  11314.                           ,isnull( max( datalength( rtrim(convert(varchar(128),cmd)))) ,7)
  11315.                          )
  11316.  
  11317.             ,@charMaxLenHostName  =
  11318.                   convert( varchar
  11319.                           ,isnull( max( datalength( rtrim(convert(varchar(128),hostname)))) ,8)
  11320.                          )
  11321.  
  11322.             ,@charMaxLenProgramName =
  11323.                   convert( varchar
  11324.                           ,isnull( max( datalength( rtrim(convert(varchar(128),program_name)))) ,11)
  11325.                          )
  11326.  
  11327.             ,@charMaxLenLastBatch =
  11328.                   convert( varchar
  11329.                           ,isnull( max( datalength( rtrim(convert(varchar(128),last_batch_char)))) ,9)
  11330.                          )
  11331.       from
  11332.              #tb1_sysprocesses
  11333.       where
  11334. --             sid >= @sidlow
  11335. --      and    sid <= @sidhigh
  11336. --      and
  11337.              spid >= @spidlow
  11338.       and    spid <= @spidhigh
  11339.  
  11340.  
  11341.  
  11342. --------Output the report.
  11343.  
  11344.  
  11345. EXECUTE(
  11346. '
  11347. SET nocount off
  11348.  
  11349. SELECT
  11350.              SPID          = convert(char(5),spid)
  11351.  
  11352.             ,Status        =
  11353.                   CASE lower(status)
  11354.                      When ''sleeping'' Then lower(status)
  11355.                      Else                   upper(status)
  11356.                   END
  11357.  
  11358.             ,Login         = substring(loginname,1,' + @charMaxLenLoginName + ')
  11359.  
  11360.             ,HostName      =
  11361.                   CASE hostname
  11362.                      When Null  Then ''  .''
  11363.                      When '' '' Then ''  .''
  11364.                      Else    substring(hostname,1,' + @charMaxLenHostName + ')
  11365.                   END
  11366.  
  11367.             ,BlkBy         =
  11368.                   CASE               isnull(convert(char(5),blocked),''0'')
  11369.                      When ''0'' Then ''  .''
  11370.                      Else            isnull(convert(char(5),blocked),''0'')
  11371.                   END
  11372.  
  11373.             ,DBName        = substring(case when dbid = 0 then null when dbid <> 0 then db_name(dbid) end,1,' + @charMaxLenDBName + ')
  11374.             ,Command       = substring(cmd,1,' + @charMaxLenCommand + ')
  11375.  
  11376.             ,CPUTime       = substring(convert(varchar,cpu),1,' + @charMaxLenCPUTime + ')
  11377.             ,DiskIO        = substring(convert(varchar,physical_io),1,' + @charMaxLenDiskIO + ')
  11378.  
  11379.             ,LastBatch     = substring(last_batch_char,1,' + @charMaxLenLastBatch + ')
  11380.  
  11381.             ,ProgramName   = substring(program_name,1,' + @charMaxLenProgramName + ')
  11382.             ,SPID          = convert(char(5),spid)  --Handy extra for right-scrolling users.
  11383.       from
  11384.              #tb1_sysprocesses  --Usually DB qualification is needed in exec().
  11385.       where
  11386.              spid >= ' + @charspidlow  + '
  11387.       and    spid <= ' + @charspidhigh + '
  11388.  
  11389.       -- (Seems always auto sorted.)   order by spid_sort
  11390.  
  11391. SET nocount on
  11392. '
  11393. )
  11394. /*****AKUNDONE: removed from where-clause in above EXEC sqlstr
  11395.              sid >= ' + @charsidlow  + '
  11396.       and    sid <= ' + @charsidhigh + '
  11397.       and
  11398. **************/
  11399.  
  11400.  
  11401. LABEL_86RETURN:
  11402.  
  11403.  
  11404. if (object_id('tempdb..#tb1_sysprocesses') is not null)
  11405.             drop table #tb1_sysprocesses
  11406.  
  11407. return @retcode -- sp_who2
  11408. go
  11409.  
  11410.  
  11411.  
  11412. checkpoint
  11413. go
  11414.  
  11415. ---------------------------------------------------------------------------------------------
  11416. ---------------------------------------------------------------------------------------------
  11417. ---------------------------------------------------------------------------------------------
  11418.  
  11419.  
  11420. ---- Create following procs last, since they reference other procedures.
  11421.  
  11422.  
  11423.  
  11424. raiserror(15339,-1,-1,'sp_check_removable')
  11425. go
  11426. create procedure sp_check_removable @autofix varchar(4)
  11427. as
  11428.  
  11429. declare @dbosid varbinary (86)
  11430. declare @dbname sysname
  11431. declare @exec_stmt nvarchar(540)
  11432. declare @fgname sysname
  11433.  
  11434. select @dbname=db_name()
  11435.  
  11436. /* Verify that SA owns the database. */
  11437.  
  11438. select @dbosid = sid from master..sysdatabases where name = @dbname
  11439. if @dbosid <> 0x01
  11440.     if @autofix='auto'
  11441.     begin
  11442.         -- changing DBO to SA
  11443.         update sysdatabases set sid = 0x01
  11444.             where name = @dbname
  11445.         update sysusers set sid = 0x01
  11446.             where uid = 1
  11447.     end
  11448.     else
  11449.     begin
  11450.         raiserror(15258,-1,-1, @dbname)
  11451.         return(1)
  11452.     end
  11453.  
  11454.     -- USE CORRECT non-dbo/guest CHECKING
  11455.     declare @ret int
  11456.     exec @ret = sp_check_removable_sysusers @autofix
  11457.     if @ret <> 0
  11458.         return 1
  11459.  
  11460.  
  11461.     -- Run UPDATE STATISTICS on all user tables if there are
  11462.     -- no user defined filegroups
  11463.     if @autofix='auto' and
  11464.         (select count(*) from sysfilegroups) = 1
  11465.     begin
  11466.         select @exec_stmt = N'USE ' + quotename( @dbname , '[')
  11467.         + N' exec sp_updatestats ''RESAMPLE'' '
  11468.         exec (@exec_stmt)
  11469.     end
  11470.  
  11471.     exec('dump tran '+@dbname+' with no_log')
  11472.  
  11473.     if (select count(*) from sysfilegroups) > 1
  11474.     begin
  11475.         if @autofix='auto'
  11476.         begin
  11477.             -- Mark any non-primary filegroups as READONLY
  11478.             DECLARE ms_crs_fg CURSOR LOCAL STATIC
  11479.             FOR SELECT groupname FROM sysfilegroups fg
  11480.                 WHERE fg.groupid > 1 -- not primary
  11481.                 AND fg.status & 0x8 = 0 -- not already readonly
  11482.                 AND (SELECT count (*) FROM sysfiles f WHERE
  11483.                 f.groupid = fg.groupid) > 0 -- has some files
  11484.             OPEN ms_crs_fg
  11485.             FETCH NEXT FROM ms_crs_fg INTO @fgname
  11486.             WHILE (@@FETCH_STATUS <> -1)
  11487.             BEGIN
  11488.                 SELECT @exec_stmt = 'ALTER DATABASE '
  11489.                 + quotename( @dbname , '[')
  11490.                 + ' MODIFY FILEGROUP '
  11491.                 + quotename( @fgname , '[')
  11492.                 + ' READONLY'
  11493.                 EXEC (@exec_stmt)
  11494.                 FETCH NEXT FROM ms_crs_fg INTO @fgname
  11495.             END
  11496.             CLOSE ms_crs_fg
  11497.             DEALLOCATE ms_crs_fg
  11498.         end
  11499.         else
  11500.         begin
  11501.             if exists (SELECT groupname FROM sysfilegroups fg
  11502.                 WHERE fg.groupid > 1 -- not primary
  11503.                 AND fg.status & 0x8 = 0 -- not already readonly
  11504.                 AND (SELECT count (*) FROM sysfiles f WHERE
  11505.                 f.groupid = fg.groupid) > 0) -- has some files
  11506.             begin
  11507.                 raiserror(15358,-1,-1)
  11508.                 SELECT groupname FROM sysfilegroups fg
  11509.                     WHERE fg.groupid > 1 -- not primary
  11510.                     AND fg.status & 0x8 = 0 -- not already readonly
  11511.                 return (-1)
  11512.             end
  11513.         end
  11514.  
  11515.  
  11516.     end
  11517. return(0)
  11518. go
  11519.  
  11520.  
  11521. raiserror(15339,-1,-1,'sp_certify_removable')
  11522. go
  11523. CREATE PROCEDURE sp_certify_removable  --1996/03/12 12:02
  11524.  
  11525.         @dbname sysname,
  11526.         @autofix nvarchar(4) = null
  11527. as
  11528.  
  11529. set nocount on
  11530.  
  11531. declare @ret_value int,
  11532.     @char_autofix varchar(25)
  11533.  
  11534. if (not (is_srvrolemember('sysadmin') = 1))  -- Make sure that it is the SA executing this.
  11535.         begin
  11536.                 raiserror(15247,-1,-1)
  11537.                 return(1)
  11538.         end
  11539.  
  11540.  
  11541. select @autofix = lower(@autofix)
  11542.  
  11543. if @autofix <> 'auto' and @autofix is not null
  11544.         begin
  11545.                 raiserror(15255,-1,-1,@autofix)
  11546.                 return(1)
  11547.         end
  11548.  
  11549.  
  11550. if @dbname is null      -- Show usage diagram if no dbname supplied.
  11551.         begin
  11552.                 raiserror(15256,-1,-1)
  11553.                 return(1)
  11554.         end
  11555.  
  11556.  
  11557. --See if DB exists.
  11558. if not exists (select * from master.dbo.sysdatabases where name = @dbname)
  11559.         begin
  11560.                 raiserror(15010,-1,-1,@dbname)
  11561.                 return(1)
  11562.         end
  11563.  
  11564.  
  11565. --Cannot take master, tempdb or model databases offline.
  11566. if lower(@dbname) in ('master','tempdb','model')
  11567.         begin
  11568.                 raiserror(15266,-1,-1,@dbname)
  11569.                 return(1)
  11570.         end
  11571.  
  11572.  
  11573. -- Will not be able to take db offline if user is in it.
  11574. if @dbname = db_name()
  11575.         begin
  11576.                 raiserror(15257,-1,-1)
  11577.                 return(1)
  11578.         end
  11579.  
  11580. -------------  Check things that exist only in the db.  -------------------
  11581. select @char_autofix =
  11582.     CASE
  11583.        When @autofix IS NOT Null Then '''Auto'''
  11584.        Else                           'Null'
  11585.     END
  11586.  
  11587. execute(
  11588. 'use ' + @dbname + '
  11589.  
  11590. declare @inx_ret_value int ,@int1 int
  11591. select  @inx_ret_value = 1
  11592.  
  11593. exec @inx_ret_value = sp_check_removable ' + @char_autofix + '
  11594.  
  11595. --Use @@rowcount for a user_assignable global variable for communication.
  11596. if @inx_ret_value <> 0    --bad!!!!
  11597.     begin
  11598.     select @int1 = 1
  11599.     return
  11600.     end
  11601. else
  11602.     begin
  11603.     select @int1 = 1 where 1=2
  11604.     return
  11605.     end
  11606. '
  11607. )
  11608.  
  11609. if @@rowcount > 0
  11610.         return (1)  --Error was returned by other proc, so exit
  11611.  
  11612.  
  11613. -- Take it offline
  11614. raiserror('' ,0,1)
  11615. exec sp_dboption @dbname,'offline','true'
  11616.  
  11617. return(0)
  11618. go
  11619.  
  11620.  
  11621. print ' '
  11622. raiserror(15339,-1,-1,'MS_sqlctrs_users')
  11623. go
  11624. create procedure MS_sqlctrs_users --- 1996/08/30 21:49
  11625. as
  11626. select
  11627.          lg.loginname + ' - ' + convert(varchar(30),pr.spid)
  11628.         ,pr.memusage        as 'Memory (8K Pages)' -- 2K in 6.5
  11629.         ,pr.cpu            as 'CPU time'
  11630.         ,pr.physical_io
  11631.         ,count(lk.spid)        as 'Locks held'
  11632.         ,pr.spid
  11633.     from
  11634.          master.dbo.sysprocesses    pr    left outer join
  11635.          master.dbo.syslocks    lk    on pr.spid=lk.spid
  11636.         ,master.dbo.syslogins    lg
  11637.     where
  11638.          pr.sid    = lg.sid
  11639.     group by
  11640.          lg.loginname
  11641.         ,pr.spid
  11642.         ,pr.memusage
  11643.         ,pr.cpu
  11644.         ,pr.physical_io
  11645. go
  11646.  
  11647. print ' '
  11648. raiserror(15339,-1,-1,'sp_autostats')
  11649. go
  11650. CREATE PROCEDURE sp_autostats
  11651.     @tblname     nvarchar(776),
  11652.     @flagc        varchar(10)=null,
  11653.     @indname    sysname=null
  11654. AS
  11655. BEGIN
  11656.     DECLARE @flag bit, @nrc_mask int
  11657.  
  11658.     /*
  11659.     **  Check flag
  11660.     */
  11661.     SET @flag = CASE lower(@flagc)
  11662.         WHEN 'on'     THEN 1
  11663.         WHEN 'off'     THEN 0
  11664.         ELSE NULL
  11665.         END
  11666.  
  11667.     IF @flag IS NULL AND @flagc IS NOT NULL
  11668.         BEGIN
  11669.         RAISERROR(17000,-1,-1)
  11670.             RETURN (1)
  11671.         END
  11672.  
  11673.     /*
  11674.     ** Set NORECOMPUTE mask
  11675.     */
  11676.     SET @nrc_mask = 16777216
  11677.  
  11678.     /*
  11679.     ** Check we are executing in the correct database
  11680.     */
  11681.     DECLARE @db sysname
  11682.     SELECT @db = parsename(@tblname, 3)
  11683.  
  11684.     IF (@db IS NOT NULL AND @db <> db_name())
  11685.     BEGIN
  11686.         RAISERROR(15387,-1,-1)
  11687.         RETURN (1)
  11688.     END
  11689.  
  11690.     /*
  11691.     ** PRINT or UPDATE status?
  11692.     */
  11693.     IF (@flag IS NULL)
  11694.     BEGIN
  11695.  
  11696.         -- Display global settings (sp_dboption)
  11697.         --
  11698.         PRINT 'Global statistics settings for ' + quotename(db_name(), '[') + ':'
  11699.         PRINT '  Automatic update statistics: ' + (CASE WHEN DatabaseProperty(db_name(), 'IsAutoUpdateStatistics') = 1 THEN 'ON' ELSE 'OFF' END)
  11700.         PRINT '  Automatic create statistics: ' + (CASE WHEN DatabaseProperty(db_name(), 'IsAutoCreateStatistics') = 1 THEN 'ON' ELSE 'OFF' END)
  11701.         PRINT ''
  11702.  
  11703.         -- Display the current status of the index(s)
  11704.         --
  11705.         PRINT 'Settings for table ' + quotename(@tblname, '[')
  11706.         PRINT ''
  11707.         SELECT 'Index Name' = quotename(si.name, '['),
  11708.                'AUTOSTATS' =
  11709.             CASE (si.status & @nrc_mask)
  11710.                 WHEN @nrc_mask THEN 'OFF'
  11711.                 ELSE 'ON'
  11712.             END,
  11713.                'Last Updated' = stats_date(object_id(@tblname), si.indid)
  11714.         FROM sysindexes si
  11715.         WHERE si.id = object_id(@tblname) AND        -- Table
  11716.               si.indid BETWEEN 1 AND 254 AND        -- Skip HEAP/TEXT index
  11717.             CASE                     -- Match name
  11718.                 WHEN @indname IS NULL THEN 1
  11719.                 WHEN @indname = si.name THEN 1
  11720.                 ELSE 0
  11721.             END = 1
  11722.     END
  11723.     ELSE
  11724.     BEGIN
  11725.         DECLARE @_rowcount int,
  11726.                 @tabid int,
  11727.                 @objtype varchar(2)
  11728.  
  11729.         -- VERIFY WE HAVE A USER-TABLE/INDEXED-VIEW BY THIS NAME IN THE DATABASE
  11730.         SELECT @tabid = id, @objtype = xtype FROM sysobjects
  11731.             WHERE id = OBJECT_ID(@tblname, 'local') AND (xtype = 'U' OR xtype = 'V')
  11732.         IF (@tabid IS NULL OR
  11733.                 (@objtype = 'V' AND
  11734.                 (ObjectProperty(@tabid, 'IsIndexed') = 0 OR
  11735.                 ObjectProperty(@tabid, 'IsMSShipped') = 1))
  11736.             )
  11737.         begin
  11738.             raiserror(15390,-1,-1,@tblname)
  11739.             RETURN @@ERROR
  11740.         end
  11741.  
  11742.         BEGIN TRANSACTION upd_tran
  11743.  
  11744.         -- Lock the table schema and check permissions
  11745.         --
  11746.         DBCC LOCKOBJECTSCHEMA(@tblname)
  11747.  
  11748.         -- Flip the status bits
  11749.         --
  11750.         DECLARE @batch varchar(8000)
  11751.  
  11752.         UPDATE sysindexes
  11753.         SET status =
  11754.             CASE @flag
  11755.             WHEN 1 THEN status &~ @nrc_mask
  11756.             ELSE status | @nrc_mask
  11757.             END
  11758.         WHERE id = object_id(@tblname) AND        -- Table
  11759.               indid <> 255 AND                -- Skip TEXT index
  11760.               CASE                     -- Match name
  11761.             WHEN @indname IS NULL THEN 1
  11762.             WHEN @indname = name THEN 1
  11763.             ELSE 0
  11764.               END = 1
  11765.  
  11766.         -- Save the affected rowcount
  11767.         SET @_rowcount = @@rowcount
  11768.  
  11769.         COMMIT TRANSACTION upd_tran
  11770.  
  11771.         -- Show the user how many indices were affected
  11772.         PRINT 'Automatic statistics maintenance turned ' +
  11773.             CASE @flag WHEN 1 THEN 'ON' ELSE 'OFF' END +
  11774.             ' for ' + convert(varchar(5), @_rowcount) +
  11775.             ' indices.'
  11776.  
  11777.     END
  11778.  
  11779.     -- All done
  11780.     --
  11781.     RETURN(0) -- sp_autostats
  11782. END
  11783. GO
  11784.  
  11785. raiserror(15339,-1,-1,'sp_updatestats')
  11786. go
  11787. -- required for sp_updatestats so it can update stats on on ICC/IVs
  11788. set ansi_nulls on
  11789. go
  11790. CREATE PROCEDURE sp_updatestats
  11791. @resample CHAR(8)='NO'
  11792. AS
  11793.  
  11794.     DECLARE @dbsid varbinary(85)
  11795.  
  11796.     SELECT  @dbsid = sid
  11797.     FROM master.dbo.sysdatabases
  11798.     WHERE name = db_name()
  11799.  
  11800.     /*Check the user sysadmin*/
  11801.      IF NOT is_srvrolemember('sysadmin') = 1 AND suser_sid() <> @dbsid
  11802.         BEGIN
  11803.             RAISERROR(15247,-1,-1)
  11804.             RETURN (1)
  11805.         END
  11806.  
  11807.     if UPPER(@resample)<>'RESAMPLE' AND UPPER(@resample)<>'NO'
  11808.     begin
  11809.            raiserror(N'Invalid option: %s', 1, 1, @resample)
  11810.         return (1)
  11811.     end
  11812.  
  11813.     -- required so it can update stats on on ICC/IVs
  11814.     set ansi_nulls on
  11815.     set quoted_identifier on
  11816.     set ansi_warnings on
  11817.     set ansi_padding on
  11818.     set arithabort on
  11819.     set concat_null_yields_null on
  11820.     set numeric_roundabort off
  11821.  
  11822.  
  11823.  
  11824.     DECLARE @exec_stmt nvarchar(540)
  11825.     DECLARE @tablename sysname
  11826.     DECLARE @uid smallint
  11827.     DECLARE @user_name sysname
  11828.     DECLARE @tablename_header varchar(267)
  11829.     DECLARE ms_crs_tnames CURSOR LOCAL FAST_FORWARD READ_ONLY FOR SELECT name, uid FROM sysobjects WHERE type = 'U'
  11830.     OPEN ms_crs_tnames
  11831.     FETCH NEXT FROM ms_crs_tnames INTO @tablename, @uid
  11832.     WHILE (@@fetch_status <> -1)
  11833.     BEGIN
  11834.         IF (@@fetch_status <> -2)
  11835.         BEGIN
  11836.             SELECT @user_name = user_name(@uid)
  11837.             SELECT @tablename_header = 'Updating ' + @user_name +'.'+ RTRIM(@tablename)
  11838.             PRINT @tablename_header
  11839.             SELECT @exec_stmt = 'UPDATE STATISTICS ' + quotename( @user_name , '[')+'.' + quotename( @tablename, '[') 
  11840.             if (UPPER(@resample)='RESAMPLE') SET @exec_stmt = @exec_stmt + ' WITH RESAMPLE'
  11841.             EXEC (@exec_stmt)
  11842.         END
  11843.         FETCH NEXT FROM ms_crs_tnames INTO @tablename, @uid
  11844.     END
  11845.     PRINT ' '
  11846.     PRINT ' '
  11847.     raiserror(15005,-1,-1)
  11848.     DEALLOCATE ms_crs_tnames
  11849.     RETURN(0) -- sp_updatestats
  11850. go
  11851. -- was only required for sp_updatestats
  11852. set ansi_nulls off
  11853. go
  11854.  
  11855. -------------------------------- sp_createstats --------begin---------------------------
  11856. raiserror(15339,-1,-1,'sp_createstats')
  11857. go
  11858. -- required for sp_createstats so it can update stats on on ICC/IVs
  11859. set ansi_nulls on
  11860. go
  11861.  
  11862. CREATE PROCEDURE sp_createstats
  11863. @indexonly CHAR(9)= 'NO',     -- Optional 'INDEXONLY' text - if present, then only the columns
  11864.                 -- covered by indexes are subject of statistics creation
  11865. @fullscan  CHAR(9)= 'NO',      -- Optional 'FULLSCAN' text - if present, then the statistics
  11866.                 -- will be updated with full scan rather than sampling
  11867. @norecompute  CHAR(12)= 'NO'      -- Optional 'NORECOMPUTE' text - if present, then statistics
  11868.                 -- will not be updated automatically
  11869. AS
  11870. /*
  11871.     NOTE: This sp will update statistics for *all* columns of all tables
  11872.     which the user has the privilege to update stats on (sysadmin, dbo, owner).
  11873.     The following columns are not considered
  11874.     - first column of an index
  11875.     - column which already has statistics
  11876.     - unelligible columns (Text and image columns consisting of ntext, text, or image data type,
  11877.       bit, and computed columns)
  11878.  
  11879. */
  11880.  
  11881. declare @sysadmin int
  11882.     ,@dbname sysname
  11883.  
  11884. -- remember dbname
  11885.  
  11886.       SELECT @dbname = db_name()
  11887.  
  11888. -- create temporary table (column, index position)
  11889. create table #colpostab
  11890. (    col_name  sysname collate database_default ,
  11891.     col_pos      int,
  11892. )
  11893.  
  11894. set nocount on
  11895.  
  11896. -- required for sp_createstats so it can update stats on on ICC/IVs
  11897. set ansi_nulls on
  11898. set quoted_identifier on
  11899. set ansi_warnings on
  11900. set ansi_padding on
  11901. set arithabort on
  11902. set concat_null_yields_null on
  11903. set numeric_roundabort off
  11904.  
  11905. DECLARE @exec_stmt nvarchar(540)
  11906. DECLARE @tablename sysname
  11907. DECLARE @columnname sysname
  11908. --DECLARE @shortcolumnname sysname
  11909. DECLARE @indexname sysname
  11910. DECLARE @uid smallint
  11911. DECLARE @indid smallint
  11912. DECLARE @position smallint
  11913. DECLARE @table_id  int
  11914. DECLARE @user_name sysname
  11915. DECLARE @numcols int   -- number of eligible columns found
  11916. DECLARE @msg nvarchar(386)
  11917. DECLARE @timestamp varchar(17)
  11918.  
  11919. DECLARE @tablename_header varchar(267)
  11920.  
  11921. DECLARE ms_crs_tnames CURSOR LOCAL STATIC FOR
  11922. SELECT name, id, uid FROM sysobjects WHERE type = 'U' and ((object_id('[#colpostab]') is NULL) OR (id <> object_id('[#colpostab]')))
  11923.  
  11924. SELECT @numcols = 0
  11925.  
  11926. OPEN ms_crs_tnames
  11927. FETCH NEXT FROM ms_crs_tnames INTO @tablename, @table_id, @uid
  11928. WHILE (@@fetch_status <> -1)
  11929. BEGIN
  11930.     IF ((@@fetch_status <> -2) AND  (is_member('db_owner')=1) OR (is_member('ddl_admin')=1) OR (is_member(user_name(@uid))=1) OR (user_id() = @uid))
  11931.     BEGIN
  11932.         -- these are all columns for which the statistics will be updated
  11933.         DECLARE ms_crs_cnames CURSOR LOCAL FOR SELECT c.name   FROM syscolumns c, systypes t
  11934.             WHERE c.id = @table_id AND c.xtype = t.xusertype AND
  11935.                  (t.name NOT IN ('text', 'ntext', 'image', 'timestamp','bit'))
  11936.             AND ((c.colstat & 0x0004) <> 0x0004)
  11937.             AND (c.length<=900)
  11938.             AND c.name NOT IN (SELECT col_name FROM #colpostab WHERE col_pos = 1)
  11939.             AND ((c.name IN (SELECT col_name FROM #colpostab)) OR (@indexonly <> 'indexonly'))
  11940.  
  11941.         -- populate temporary table of all (column, index position) tuples for this table
  11942.  
  11943.         TRUNCATE TABLE #colpostab
  11944.  
  11945.         -- for each index on the table, loop though all columns and insert rows
  11946.         -- OPEN CURSOR OVER INDEXES
  11947.         DECLARE ms_crs_ind CURSOR LOCAL STATIC FOR
  11948.             SELECT indid, name FROM sysindexes
  11949.                 where id = @table_id and indid > 0 and indid < 255 order by indid
  11950.  
  11951.         OPEN ms_crs_ind
  11952.         FETCH ms_crs_ind into @indid , @indexname
  11953.  
  11954.         -- IF AN INDEX EXISTS
  11955.  
  11956.         WHILE @@fetch_status >= 0
  11957.         BEGIN
  11958.             -- Every index has at least one column at position 1
  11959.             INSERT INTO #colpostab VALUES (index_col(@tablename,@indid,1),1)
  11960.             -- now try position 2 and beyond....
  11961.             SELECT @columnname = index_col(@tablename, @indid, 2)
  11962.             SELECT @position = 2
  11963.             WHILE (@columnname is not null )
  11964.                 BEGIN
  11965.                     INSERT INTO #colpostab VALUES (@columnname,@position)
  11966.                     SELECT @position = @position +1
  11967.                     SELECT @columnname = index_col(@tablename, @indid, @position)
  11968.                 END
  11969.             -- Next Index
  11970.             FETCH ms_crs_ind into @indid , @indexname
  11971.  
  11972.         END
  11973.         CLOSE ms_crs_ind
  11974.         DEALLOCATE ms_crs_ind
  11975.  
  11976.         -- now go over all columns which are eligible for updating statistics
  11977.         -- and are not first columns of any index
  11978.         -- optionaly we test if they are covered by some index (as non-leading)
  11979.  
  11980.         SELECT @user_name = user_name(@uid)
  11981.  
  11982.         OPEN ms_crs_cnames
  11983.  
  11984.         FETCH NEXT FROM ms_crs_cnames INTO @columnname
  11985.         IF @@fetch_status < 0
  11986.         BEGIN
  11987.             select @msg = @dbname +'.'+ @user_name +'.'+ @tablename
  11988.             raiserror(15013,-1,-1,@msg)
  11989.         END
  11990.         ELSE
  11991.         BEGIN
  11992.             select @msg = @dbname +'.'+ @user_name +'.'+ @tablename
  11993.             raiserror(15018, -1, -1, @msg)
  11994.         END
  11995.  
  11996.         WHILE @@fetch_status >= 0
  11997.         BEGIN
  11998.               SELECT @numcols = @numcols +1
  11999.              -- use the column name as the name for the statistics as well
  12000.              select @exec_stmt = 'CREATE STATISTICS ' +  quotename(@columnname, '[')  + ' ON ' +
  12001.          quotename( @user_name ,'[')+'.' + quotename( @tablename, '[')+'('+ quotename( @columnname, '[')+')'
  12002.             -- determining the correct suffix
  12003.             if ((@fullscan = 'FULLSCAN') AND (@norecompute = 'NORECOMPUTE'))
  12004.                 select @exec_stmt = @exec_stmt + ' WITH FULLSCAN, NORECOMPUTE'
  12005.             else if (@fullscan = 'FULLSCAN') select @exec_stmt = @exec_stmt + ' WITH FULLSCAN'
  12006.             else if (@norecompute = 'NORECOMPUTE') select @exec_stmt = @exec_stmt + ' WITH NORECOMPUTE'
  12007.             EXEC (@exec_stmt)
  12008.             --PRINT 'Statement='+@exec_stmt
  12009.             if (@@ERROR = 0)  -- otherwise the CREATE STATS will give a message
  12010.                  PRINT '     ' + @columnname
  12011.             FETCH NEXT FROM ms_crs_cnames INTO @columnname
  12012.         END
  12013.         CLOSE ms_crs_cnames
  12014.         DEALLOCATE ms_crs_cnames
  12015.     END
  12016.     FETCH NEXT FROM ms_crs_tnames INTO @tablename, @table_id, @uid
  12017. END
  12018.  
  12019. PRINT ' '
  12020. raiserror(15020,-1,-1,@numcols)
  12021.  
  12022. DEALLOCATE ms_crs_tnames
  12023.  
  12024. IF (object_id('[#colpostab]') is not null)
  12025.    begin
  12026.             drop table [#colpostab]
  12027.    end
  12028.  
  12029. return(0) -- sp_createstats
  12030. go
  12031. -- was only required for sp_createstats
  12032. set ansi_nulls off
  12033. go
  12034.  
  12035. ------------------------------- sp_cycle_errorlog -----------------------------------
  12036. raiserror(15339,-1,-1,'sp_cycle_errorlog')
  12037. go
  12038. create procedure sp_cycle_errorlog  --- 1997/06/24
  12039. as
  12040. if (not (is_srvrolemember('sysadmin') = 1))  -- Make sure that it is the SA executing this.
  12041.         begin
  12042.                 raiserror(15247,-1,-1)
  12043.                 return(1)
  12044.         end
  12045.  
  12046. dbcc errorlog
  12047. return (0)
  12048. go
  12049.  
  12050.  
  12051.  
  12052.  
  12053.  
  12054. -------------------------------- sp_helptrigger -----------------------------------
  12055.  
  12056. raiserror(15339,-1,-1,'sp_helptrigger')
  12057. go
  12058. create procedure sp_helptrigger  --- 1997/06/24
  12059.     @tabname nvarchar(776),            /*    Table name        */
  12060.     @triggertype char(6) = NULL    /*    Trigger type    */
  12061. as
  12062.  
  12063. declare @objid int,        /* id of the object */
  12064.         @dbname sysname,
  12065.         @deltrig int,
  12066.         @instrig int,
  12067.         @updtrig int
  12068.  
  12069. -- Check to see that the object names are local to the current database.
  12070. select @dbname = parsename(@tabname,3)
  12071.  
  12072. if @dbname is not null and @dbname <> db_name()
  12073. begin
  12074.         raiserror(15250,-1,-1)
  12075.         return (1)
  12076. end
  12077.  
  12078. select @objid =  id from sysobjects where id = object_id(@tabname)
  12079.     and type in ('S','U', 'V')
  12080.  
  12081. if @objid is null
  12082.     begin
  12083.         select @dbname = db_name()
  12084.         raiserror(15009,-1,-1,@tabname,@dbname)
  12085.         return(1)
  12086.     end
  12087.  
  12088. /*    Check that input type is UPDATE, INSERT, DELETE    */
  12089. if @triggertype  is not null and not UPPER(@triggertype ) in ('UPDATE', 'INSERT', 'DELETE')
  12090.       begin
  12091.          raiserror(15305,-1,-1)
  12092.          return(1)
  12093.       end
  12094.  
  12095. if @triggertype  is NULL
  12096.     select
  12097.     trigger_name = name,
  12098.     trigger_owner = user_name(uid),
  12099.     isupdate = ObjectProperty( id, 'ExecIsUpdateTrigger'),
  12100.     isdelete = ObjectProperty( id, 'ExecIsDeleteTrigger'),
  12101.     isinsert = ObjectProperty( id, 'ExecIsInsertTrigger'),
  12102.     isafter = ObjectProperty( id, 'ExecIsAfterTrigger'),
  12103.     isinsteadof = ObjectProperty( id, 'ExecIsInsteadOfTrigger')
  12104.     from sysobjects
  12105.     where parent_obj = @objid and type = 'TR'
  12106. else
  12107. begin
  12108.     set @deltrig = case
  12109.         when  upper(@triggertype ) = 'DELETE' then 0
  12110.         else -1 end
  12111.     set @instrig = case
  12112.         when  upper(@triggertype ) = 'INSERT' then 0
  12113.         else  -1 end
  12114.     set @updtrig = case
  12115.         when  upper(@triggertype ) = 'UPDATE' then 0
  12116.         else -1 end
  12117.     select
  12118.     trigger_name = name,
  12119.     trigger_owner = user_name(uid),
  12120.     isupdate = ObjectProperty( id, 'ExecIsUpdateTrigger'),
  12121.     isdelete = ObjectProperty( id, 'ExecIsDeleteTrigger'),
  12122.     isinsert = ObjectProperty( id, 'ExecIsInsertTrigger'),
  12123.     isafter = ObjectProperty( id, 'ExecIsAfterTrigger'),
  12124.     isinsteadof = ObjectProperty( id, 'ExecIsInsteadOfTrigger')
  12125.     from sysobjects
  12126.     where parent_obj = @objid and
  12127.     ObjectProperty( id, 'ExecIsDeleteTrigger') > @deltrig and
  12128.     ObjectProperty( id, 'ExecIsInsertTrigger') > @instrig and
  12129.     ObjectProperty( id, 'ExecIsUpdateTrigger') > @updtrig and
  12130.     type = 'TR'
  12131. end
  12132. return(0)  --sp_helptrigger
  12133. go
  12134.  
  12135. raiserror(15339,-1,-1,'sp_fixindex')
  12136. go
  12137. create procedure sp_fixindex
  12138.         @dbname        sysname,
  12139.         @tabname    sysname,                  /* system table name */
  12140.         @indid        int                        /* index id value    */
  12141. as
  12142.  
  12143.     declare @indexname sysname
  12144.     /*
  12145.     **    Description:    allow the SA to force a drop and then a
  12146.     **            create index on system catalogs.
  12147.     **
  12148.     **    Usage:        sp_fixindex  database, systemcatalog, ind_id
  12149.     **
  12150.     **    Note:        before using this procedure the database has to
  12151.     **            be in single user mode. The sp_dboption has to
  12152.     **            be used for user databases, and update of
  12153.     **            sysdatabases for master.
  12154.     **
  12155.     */
  12156.  
  12157.     /* Check that current db is db for processing*/
  12158.     if db_name() <> @dbname
  12159.         begin
  12160.             raiserror(15555,-1,-1, @dbname)
  12161.             return(1)
  12162.         end
  12163.  
  12164.     /*
  12165.     **    Make sure we are 'fixing' a system catalog.
  12166.     */
  12167.     if not exists (select name from sysobjects where name = @tabname and type = 'S')
  12168.         begin
  12169.             raiserror(15193,-1,-1)
  12170.             return (1)
  12171.         end
  12172.  
  12173.  
  12174.     /* Check database is in single user mode */
  12175.     if ((select status from master..sysdatabases where name = @dbname) &
  12176.        (select number from master..spt_values where name = 'single user' and  type = 'D') = 0) and
  12177.        (select value from master..syscurconfigs where config = 102) <> 1
  12178.         begin
  12179.             raiserror(15308,-1,-1, @dbname)
  12180.             return(1)
  12181.         end
  12182.  
  12183.     /*
  12184.     **    Make sure that we are doing this on somenthing that
  12185.     **    has indexes (or real tables).
  12186.     */
  12187.     if exists (select id from sysindexes where id = object_id(@tabname) and status & 8 <> 0)
  12188.         begin
  12189.             raiserror(15194,-1,-1)
  12190.             return (1)
  12191.         end
  12192.  
  12193.     /* Get the index name    */
  12194.     select @indexname = name from sysindexes where id = object_id(@tabname) and  indid = @indid
  12195.  
  12196.     if @indexname is null
  12197.         begin
  12198.             raiserror(15323,-1,-1, @tabname)
  12199.             return (1)
  12200.         end
  12201.  
  12202.     if (object_id(@tabname) <= 100)
  12203.         begin
  12204.             dbcc dbrepair(@dbname, repairindex, @tabname, @indid)
  12205.         end
  12206.     else
  12207.         begin
  12208.             dbcc dbreindex(@tabname, @indexname)
  12209.         end
  12210.  
  12211.     return (0)
  12212. go
  12213.  
  12214. ------------------------------- sp_settriggerorder ---------------------------------
  12215.  
  12216. if object_id('sp_settriggerorder','P') IS NOT NULL
  12217.     drop procedure sp_settriggerorder
  12218. go
  12219. raiserror(15339,-1,-1,'sp_settriggerorder')
  12220. go
  12221. create procedure sp_settriggerorder
  12222.     @triggername    nvarchar(517),    -- name of the trigger (may be 2-part)
  12223.     @order            varchar(10),    -- first, last, or none
  12224.     @stmttype        varchar(10)        -- insert, update, or delete
  12225. as
  12226.     set nocount on
  12227.     declare @firstbit        int        -- bit for first-trigger of given @stmttype
  12228.             ,@lastbit        int        -- bit for last-trigger of given @stmttype
  12229.             ,@setbit        int        -- status bit to set (0 for clear) based on @stmttype/@order
  12230.             ,@trigid        int        -- objid of the trigger
  12231.             ,@tableid        int        -- objid of the trigger's table
  12232.             ,@uid            smallint --user id
  12233.             ,@tabname        nvarchar(517)    -- name of the trigger's table
  12234.  
  12235.     -- VALIDATE PARAMETERS and obtain bits affected --
  12236.     SELECT @order = rtrim(@order), @stmttype = rtrim(@stmttype)
  12237.     SELECT @firstbit = case lower(@stmttype)
  12238.                 when 'delete' then 16384
  12239.                 when 'update' then 65536
  12240.                 when 'insert' then 262144
  12241.                 else NULL end
  12242.     SELECT @lastbit = @firstbit * 2        -- NOTE DEPENDENCY ON BIT LAYOUT HERE!
  12243.     SELECT @setbit = case lower(@order)
  12244.                 when 'none' then 0
  12245.                 when 'first' then @firstbit
  12246.                 when 'last' then @lastbit
  12247.                 else NULL end
  12248.     IF @setbit is NULL OR @firstbit IS NULL
  12249.     begin
  12250.         raiserror(15600,-1,-1, 'sp_settriggerorder')
  12251.         return (1)
  12252.     end
  12253.  
  12254.     -- BEGIN TRAN AND LOCK SCHEMA (also checks permissions) --
  12255.     BEGIN TRAN
  12256.     DBCC LOCKOBJECTSCHEMA(@triggername)
  12257.     if @@error <> 0
  12258.         goto abort_exit
  12259.  
  12260.     -- VERIFY PROPER OBJECT TYPE --
  12261.     select @trigid = object_id(@triggername, 'local')
  12262.     select @tableid = parent_obj, @uid = uid from sysobjects where id = @trigid AND xtype='TR'
  12263.         and ObjectProperty(@trigid,'ExecIsInsteadofTrigger')=0
  12264.         and ObjectProperty(@trigid,'ExecIs'+@stmttype+'Trigger')=1
  12265.     if (@tableid is NULL)
  12266.     begin
  12267.         if ObjectProperty(@trigid,'ExecIs'+@stmttype+'Trigger')=0
  12268.             raiserror(15125,-1,-1, @triggername, @stmttype)
  12269.         else if ObjectProperty(@trigid,'ExecIsInsteadofTrigger')=1
  12270.             raiserror(15133, -1, -1, @triggername)
  12271.         else
  12272.             raiserror(15126,-1,-1,@triggername)
  12273.         goto abort_exit
  12274.     end
  12275.  
  12276.     -- LOCK THE TABLE SCHEMA TOO --
  12277.     select @tabname = quotename(user_name(@uid))+'.'+quotename(object_name(@tableid))
  12278.     DBCC LOCKOBJECTSCHEMA(@tabname)
  12279.     if @@error <> 0
  12280.         goto abort_exit
  12281.  
  12282.     -- VERIFY FIRST/LAST OF GIVEN TYPE DOESN'T ALREADY EXIST --
  12283.     IF EXISTS (select * from sysobjects where parent_obj = @tableid AND xtype='TR' AND id <> @trigid
  12284.              AND ObjectProperty(id, 'ExecIs'+@order+@stmttype+'Trigger') = 1)
  12285.     BEGIN
  12286.         raiserror(15130,-1,-1,@tabname, @order, @stmttype)
  12287.         goto abort_exit
  12288.     END
  12289.  
  12290.     -- SET THE ORDER AS REQUESTED, COMMIT & RETURN SUCCESS --
  12291.     update sysobjects set status = ((status&~(@firstbit|@lastbit))|@setbit) where id = @trigid
  12292.     commit transaction
  12293.     return(0)
  12294.  
  12295.     -- ROLLBACK TRAN & EXIT-FAIL --
  12296. abort_exit:
  12297.     rollback transaction
  12298.     return(1)
  12299. go
  12300.  
  12301. grant execute on sp_settriggerorder to public
  12302. go
  12303.  
  12304.  
  12305. /**********************EXTENDED PROPERTY SPS**********************************/
  12306. raiserror(15339,-1,-1,'system_function_schema.fn_listextendedproperty')
  12307. go
  12308. create function system_function_schema.fn_listextendedproperty
  12309.     (@name sysname                = NULL,
  12310.     @level0type    varchar(128)    = NULL,
  12311.     @level0name    sysname            = NULL,
  12312.     @level1type    varchar(128)    = NULL,
  12313.     @level1name    sysname            = NULL,
  12314.     @level2type    varchar(128)    = NULL,
  12315.     @level2name    sysname            = NULL
  12316. )
  12317.  
  12318. returns @tab table(objtype varchar(128) null,
  12319.         objname sysname null,
  12320.         name sysname not null,
  12321.         value sql_variant null)
  12322. as
  12323. begin
  12324.  
  12325. declare @objtype varchar(2),
  12326.         @colnum smallint
  12327.  
  12328.  
  12329. select    @level0type    = UPPER(@level0type)
  12330.         ,@level1type    = UPPER(@level1type)
  12331.         ,@level2type    = UPPER(@level2type)
  12332.  
  12333. if @level0type is null and @level0name is null
  12334. begin
  12335.     if    @level1type is null and @level1name is null and
  12336.         @level2type is null and @level2name is null
  12337.     begin
  12338.         insert @tab
  12339.         select NULL,NULL, name, value
  12340.         from sysproperties
  12341.         where    type = 0 and is_member('db_owner') = 1 and
  12342.             (@name is null or @name = name)
  12343.     end
  12344.  
  12345.     return
  12346. end
  12347.  
  12348. if    @level1type is null and @level1name is null and
  12349.     @level2type is null and @level2name is null
  12350. begin
  12351.     if @level0type = 'TYPE'
  12352.     begin
  12353.         insert @tab
  12354.         select @level0type, t.name, p.name, p.value
  12355.         from sysproperties p, systypes t
  12356.         where    p.type = 1 and p.id = 0 and p.smallid = xusertype and
  12357.             (@level0name is null or t.name = @level0name) and
  12358.             (@name is null or @name = p.name)
  12359.     end
  12360.     else if @level0type = 'USER'
  12361.     begin
  12362.         insert @tab
  12363.         select @level0type, u.name, p.name, p.value
  12364.         from sysusers u, sysproperties p
  12365.         where p.type = 2 and p.id = 0 and p.smallid = uid and
  12366.             (is_member('db_owner') = 1 or is_member(u.name) = 1) and
  12367.             (@level0name is null or u.name = @level0name) and
  12368.             (@name is null or @name = p.name)
  12369.     end
  12370.     return
  12371. end
  12372. if @level0type is null or @level0name is null or @level0type <> 'USER'
  12373.     return
  12374.  
  12375. if @level2type is null and @level2name is null
  12376. begin
  12377.     if @level1type in ('TABLE', 'VIEW', 'PROCEDURE', 'RULE', 'DEFAULT')
  12378.     begin
  12379.         select @objtype = case @level1type
  12380.                     when 'TABLE' then 'U'
  12381.                     when 'VIEW' then 'V'
  12382.                     when 'PROCEDURE' then 'P'
  12383.                     when 'RULE' then 'R'
  12384.                     when 'DEFAULT' then 'D'
  12385.                     end
  12386.  
  12387.         insert @tab
  12388.         select @level1type, o.name, p.name, p.value
  12389.         from sysobjects o, sysproperties p
  12390.         where    p.type = 3 and p.smallid = 0 and o.id = p.id and
  12391.                 (permissions(o.id) > 0 or @objtype in ('R', 'D')) and
  12392.                 o.uid = user_id(@level0name) and
  12393.                 o.xtype = @objtype and o.parent_obj = 0 and
  12394.                 (@level1name is null or o.name = @level1name) and
  12395.                 (@name is null or @name = p.name)
  12396.  
  12397.     end
  12398.     else if (@level1type = 'FUNCTION')
  12399.     begin
  12400.             insert @tab
  12401.             select @level1type, o.name, p.name, p.value
  12402.             from sysobjects o, sysproperties p
  12403.             where    p.type = 3 and p.smallid = 0 and o.id = p.id and
  12404.                     permissions(o.id) > 0 and
  12405.                     o.uid = user_id(@level0name) and
  12406.                     o.xtype in ('TF','FN','IF') and
  12407.                     (@level1name is null or o.name = @level1name) and
  12408.                     (@name is null or @name = p.name)
  12409.     end
  12410.  
  12411.     return
  12412. end
  12413. if @level1type is null or @level1name is null
  12414.     return
  12415.  
  12416. if @level2type = 'COLUMN'
  12417. begin
  12418.     if @level1type not in ('TABLE', 'VIEW', 'FUNCTION')
  12419.         return
  12420.  
  12421.     insert @tab
  12422.     select @level2type, c.name, p.name, p.value
  12423.     from syscolumns c, sysproperties p, sysobjects o
  12424.     where    p.type = 4 and p.smallid = c.colid and
  12425.             c.id = object_id(quotename(@level0name)+'.'+quotename(@level1name)) and
  12426.             c.id = p.id and permissions(c.id,c.name) > 0 and c.number = 0 and
  12427.             (@level2name is null or c.name = @level2name) and
  12428.             (@name is null or @name = p.name) and
  12429.             c.id = o.id and o.xtype in ('U','V','TF','IF')
  12430.  
  12431. end
  12432. else if @level2type ='TRIGGER'
  12433. begin
  12434.     if @level1type not in ('TABLE', 'VIEW')
  12435.         return
  12436.  
  12437.     insert @tab
  12438.     select @level2type, o.name, p.name, p.value
  12439.         from sysobjects o, sysproperties p
  12440.         where    p.type = 3 and p.smallid = 0 and p.id = o.id and
  12441.             o.parent_obj = object_id(quotename(@level0name)+'.'+quotename(@level1name)) and
  12442.             permissions(o.parent_obj) > 0 and
  12443.             o.xtype = 'TR' and
  12444.             (@level2name is null or o.name = @level2name) and
  12445.             (@name is null or @name = p.name)
  12446.  
  12447. end
  12448. else if @level2type = 'CONSTRAINT'
  12449. begin
  12450.     if @level1type not in ('TABLE', 'FUNCTION')
  12451.         return
  12452.  
  12453.     insert @tab
  12454.     select @level2type, o.name, p.name, p.value
  12455.         from sysobjects o, sysproperties p
  12456.         where    p.type = 3 and p.smallid = 0 and p.id = o.id and
  12457.             o.parent_obj = object_id(quotename(@level0name)+'.'+quotename(@level1name)) and
  12458.             permissions(o.parent_obj) > 0 and
  12459.             o.xtype in ('C','D','F','PK','UQ') and
  12460.             (@level2name is null or o.name = @level2name) and
  12461.             (@name is null or @name = p.name)
  12462.  
  12463. end
  12464. else if @level2type = 'INDEX'
  12465. begin
  12466.     if @level1type not in ('TABLE', 'VIEW')
  12467.         return
  12468.  
  12469.     insert @tab
  12470.     select @level2type, i.name, p.name, p.value
  12471.         from sysindexes i, sysproperties p
  12472.         where    p.type = 6 and permissions(i.id) > 0 and
  12473.             p.id = object_id(quotename(@level0name)+'.'+quotename(@level1name)) and
  12474.             p.smallid = i.indid and i.id = p.id and
  12475.             (@level2name is null or i.name = @level2name) and
  12476.             (@name is null or @name = p.name) and
  12477.             i.indid not in (0,255) and i.status&0x1800 = 0    -- no PK/UQ constraint
  12478. end
  12479. else if @level2type = 'PARAMETER'
  12480. begin
  12481.     if @level1type not in ('PROCEDURE', 'FUNCTION')
  12482.         return
  12483.  
  12484.     select @objtype = xtype from sysobjects where id = object_id(quotename(@level0name)+'.'+quotename(@level1name))
  12485.     select @colnum = case  @objtype when 'FN' then 0 else 1 end
  12486.  
  12487.     insert @tab
  12488.     select @level2type, c.name, p.name, p.value
  12489.     from syscolumns c, sysproperties p
  12490.     where    p.type = 5 and p.smallid = c.colid and
  12491.             c.id = object_id(quotename(@level0name)+'.'+quotename(@level1name)) and
  12492.             c.id = p.id and permissions(c.id) > 0 and c.number = @colnum and
  12493.             (@level2name is null or c.name = @level2name) and
  12494.             (@name is null or @name = p.name) and
  12495.             @objtype in ('P', 'TF','FN','IF')
  12496. end
  12497.  
  12498. return
  12499. end
  12500. go
  12501.  
  12502. raiserror(15339,-1,-1,'sp_validatepropertyinputs')
  12503. go
  12504. create procedure sp_validatepropertyinputs
  12505.     @name            sysname
  12506.     ,@level0type        varchar(128)
  12507.     ,@level0name        sysname
  12508.     ,@level1type        varchar(128)
  12509.     ,@level1name        sysname
  12510.     ,@level2type        varchar(128)
  12511.     ,@level2name        sysname
  12512.     ,@id                int                OUTPUT
  12513.     ,@smallid            smallint        OUTPUT
  12514.     ,@type                tinyint            OUTPUT
  12515.     ,@exists            int                OUTPUT
  12516.     ,@fullname            nvarchar(400)    OUTPUT
  12517.     ,@objname            nvarchar(517)    OUTPUT        -- level 1 object name
  12518.  
  12519. as
  12520. -----------------------------------------------------
  12521. -- NOTE: FOR INTERNAL USE ONLY (sp_addextendedproperty,sp_updateextendedproperty,sp_dropextendedproperty)
  12522. --      DO NOT DOCUMENT OR USE!
  12523. -----------------------------------------------------
  12524.  
  12525.     declare @ret int
  12526.  
  12527.     select @id = 0, @smallid = 0    --Initialize 0 is used instead of null
  12528.  
  12529.     Select    @level0type        = UPPER(@level0type)
  12530.             ,@level1type    = UPPER(@level1type)
  12531.             ,@level2type    = UPPER(@level2type)
  12532.  
  12533.     declare @invalidlevel varchar(25)
  12534.             ,@objtype varchar(2)
  12535.             ,@uid int
  12536.             ,@objid int
  12537.             ,@lev2objexists tinyint
  12538.  
  12539.     if @name is null
  12540.         return (2)    --return to calling proc which will raiserror
  12541.  
  12542.     execute @ret = sp_validname @name
  12543.     if (@ret <> 0)
  12544.         return (1)
  12545.  
  12546.  
  12547.     if (@level2type is not null and
  12548.         (@level1type is null or @level0type is null)) or
  12549.         (@level1type is not null and @level0type is null)
  12550.             return (2)    --return to called proc which will raiserror
  12551.  
  12552.     select @fullname =
  12553.         case
  12554.             when (@level2name is not null) then
  12555.                 @level0name + '.' + @level1name + '.' + @level2name
  12556.              when (@level1name is not null) then
  12557.                 @level0name + '.' + @level1name
  12558.             when (@level0name is not null) then
  12559.                 @level0name
  12560.         end
  12561.     select @fullname = isnull(@fullname,'object specified')
  12562.  
  12563.     if @level0type is null and @level0name is null
  12564.     begin
  12565.  
  12566.         --must be dbo 
  12567.         if is_member('db_owner') = 0
  12568.         begin
  12569.             raiserror(15247,-1,-1)
  12570.             return (1)
  12571.         end
  12572.  
  12573.         --Database Property
  12574.         select    @type = 0 --Indicates database entry
  12575.  
  12576.     end
  12577.     else if @level0type = 'TYPE' and @level0name is not null
  12578.     begin
  12579.  
  12580.         select    @smallid = xusertype,@type = 1
  12581.         from    systypes
  12582.         where    name = @level0name and xusertype > 256 --only udtypes
  12583.  
  12584.     end
  12585.     else if @level0type = 'USER' and @level0name is not null
  12586.     begin
  12587.  
  12588.         select    @type = 2, @smallid = uid
  12589.         from    sysusers
  12590.         where    name = @level0name and
  12591.                 (issqluser = 1 or isntname = 1 or @level1type is not null) and --no alias/should only be users (any owner ok for objects)
  12592.                 uid NOT IN (3,4) --no INFORMATION_SCHEMA, system_function_schema
  12593.  
  12594.     end
  12595.     else
  12596.         return (2)    --return to called proc which will raiserror
  12597.  
  12598.  
  12599.     --Check is user/type does not exits then @type will be null
  12600.     if @type is null or
  12601.     (@level1type is null and @smallid in (1,2)) --Not permitted to add prop to dbo/guest
  12602.     begin
  12603.         raiserror(15135,-1,-1,@fullname)
  12604.         return (1)
  12605.     end
  12606.  
  12607.     if @level1type in ('TABLE', 'VIEW', 'PROCEDURE', 'RULE', 'DEFAULT', 'FUNCTION')
  12608.             and @level1name is not null
  12609.     begin
  12610.  
  12611.         if not (@level0type = 'USER')
  12612.             return (2)    --return to called proc which will raiserror
  12613.  
  12614.         --Not for temp tables
  12615.         if substring(@level1name,1,1) = N'#'
  12616.         begin
  12617.             raiserror(15135,-1,-1,@fullname)
  12618.             return (1)
  12619.         end
  12620.  
  12621.         select @uid = @smallid
  12622.         select @smallid = 0
  12623.  
  12624.         if (@level1type = 'FUNCTION')
  12625.         begin
  12626.             select    @id = id,@type = 3, @objtype = xtype
  12627.             from    sysobjects
  12628.             where    name = @level1name and uid = @uid and
  12629.                     xtype in ('FN','TF','IF') and parent_obj = 0
  12630.         end
  12631.         else
  12632.         begin
  12633.         --Can only be for objects and not default/rule constraints
  12634.             select @objtype = case @level1type
  12635.                         when 'TABLE' then 'U'
  12636.                         when 'VIEW' then 'V'
  12637.                         when 'PROCEDURE' then 'P'
  12638.                         when 'RULE' then 'R'
  12639.                         when 'DEFAULT' then 'D'
  12640.                     end
  12641.  
  12642.             select    @id = id,@type = 3
  12643.             from    sysobjects
  12644.             where    name = @level1name and uid = @uid and
  12645.                     xtype = @objtype and parent_obj = 0
  12646.         end
  12647.         --if object not found than @id will = 0
  12648.         if @id = 0
  12649.         begin
  12650.             raiserror(15135,-1,-1, @fullname)
  12651.             return (1)
  12652.         end
  12653.  
  12654.         select @objname = QUOTENAME(@level0name) + '.' + QUOTENAME(@level1name)
  12655.  
  12656.     end
  12657.     else if not (@level1type is null and @level1name is null)
  12658.         return (2)    --return to called proc which will raiserror
  12659.  
  12660.     --Check Permissions
  12661.     if @id <> 0 and
  12662.         is_member('db_owner') = 0 and is_member(@level0name) = 0
  12663.         and is_member('db_ddladmin') = 0
  12664.     begin
  12665.         raiserror(15247,-1,-1)
  12666.         return (1)
  12667.     end
  12668.     else if @smallid <> 0 and is_member('db_owner') = 0 and
  12669.         (@level0type = 'USER') OR
  12670.         -- For type: may also be db_ddladmin or an owner
  12671.         (@level0type = 'TYPE' and is_member('db_ddladmin')=0 and
  12672.             is_member(user_name((select uid from systypes where xusertype=@smallid)))=0)
  12673.     begin
  12674.         raiserror(15247,-1,-1)
  12675.         return (1)
  12676.     end
  12677.  
  12678.     if @level2type = 'COLUMN'  and @level2name is not null
  12679.     begin
  12680.  
  12681.         if @level1type not in ('TABLE','VIEW','FUNCTION')
  12682.             return (2)    --return to called proc which will raiserror
  12683.  
  12684.         select    @smallid = colid, @type = 4,@lev2objexists = 1
  12685.         from    syscolumns
  12686.         where    id = @id and name = @level2name and
  12687.                 number = 0    --specified columns entry
  12688.  
  12689.     end
  12690.     else if @level2type = 'PARAMETER' and @level2name is not null
  12691.     begin
  12692.  
  12693.         if @level1type not in ('PROCEDURE','FUNCTION')
  12694.             return (2)    --return to called proc which will raiserror
  12695.  
  12696.         --scalar function params have number as 0 for params
  12697.         if @objtype = 'FN'
  12698.             select    @smallid = colid, @type = 5,@lev2objexists = 1
  12699.             from    syscolumns
  12700.             where    id = @id and name = @level2name and
  12701.                     number = 0    --specified parameter entry
  12702.  
  12703.         else
  12704.             select    @smallid = colid, @type = 5,@lev2objexists = 1
  12705.             from    syscolumns
  12706.             where    id = @id and name = @level2name and
  12707.                     number = 1    --specified parameter entry
  12708.  
  12709.     end
  12710.     else if @level2type ='TRIGGER' and @level2name is not null
  12711.     begin
  12712.  
  12713.         if @level1type not in ('TABLE','VIEW')
  12714.             return (2)    --return to called proc which will raiserror
  12715.  
  12716.         select @objid = @id
  12717.         select @id = 0
  12718.  
  12719.         select    @id = id, @type = 3, @lev2objexists = 1
  12720.         from    sysobjects
  12721.         where    name = @level2name and parent_obj = @objid and
  12722.                 xtype = N'TR'
  12723.  
  12724.     end
  12725.     else if @level2type = 'CONSTRAINT' and @level2name is not null
  12726.     begin
  12727.  
  12728.         if not @level1type in ('TABLE','FUNCTION')
  12729.             return (2)    --return to called proc which will raiserror
  12730.  
  12731.         select @objid = @id
  12732.         select @id = 0
  12733.  
  12734.         select    @id = id, @type = 3, @lev2objexists = 1
  12735.         from    sysobjects
  12736.         where    name = @level2name and parent_obj = @objid and
  12737.                 xtype in ('C','D','F', 'PK', 'UQ')
  12738.  
  12739.     end
  12740.     else if @level2type = 'INDEX' and @level2name is not null
  12741.     begin
  12742.  
  12743.         if not @level1type in ('TABLE', 'VIEW')
  12744.             return (2)    --return to called proc which will raiserror
  12745.  
  12746.         select    @smallid = indid, @type = 6, @lev2objexists = 1
  12747.         from    sysindexes
  12748.         where    name = @level2name and id = @id and
  12749.                 indid not in (0,255) and status&0x1800 = 0 --no PK/U constraints
  12750.  
  12751.     end
  12752.     else if not (@level2type is null and @level2name is null)
  12753.             return (2)    --return to called proc which will raiserror
  12754.  
  12755.     --Does the level2 obj exists
  12756.     if @lev2objexists is null and @level2type is not null
  12757.     begin
  12758.         raiserror(15135,-1,-1, @fullname)
  12759.         return (1)
  12760.     end
  12761.  
  12762.     --Check if property exists
  12763.     select @exists = (select count(*) from sysproperties
  12764.                     where    @type = type and
  12765.                         @id =    id    and
  12766.                         @smallid =    smallid    and
  12767.                         @name = name)
  12768.  
  12769.     return (0)
  12770. go
  12771.  
  12772. raiserror(15339,-1,-1,'sp_addextendedproperty')
  12773. go
  12774. create procedure sp_addextendedproperty
  12775.     @name sysname,
  12776.     @value sql_variant            = NULL,
  12777.     @level0type    varchar(128)    = NULL,
  12778.     @level0name    sysname            = NULL,
  12779.     @level1type    varchar(128)    = NULL,
  12780.     @level1name    sysname            = NULL,
  12781.     @level2type    varchar(128)    = NULL,
  12782.     @level2name    sysname            = NULL
  12783. as
  12784.  
  12785.     declare @id int
  12786.         ,@smallid smallint
  12787.         ,@type tinyint
  12788.         ,@ret int
  12789.         ,@exists int
  12790.         ,@fullname nvarchar(400)
  12791.         ,@objname nvarchar(517)
  12792.  
  12793.         if datalength(@value) > 7500
  12794.         begin
  12795.             raiserror(15097,-1,-1)
  12796.             return 1
  12797.         end
  12798.  
  12799.         execute @ret = sp_validatepropertyinputs
  12800.                         @name
  12801.                         ,@level0type
  12802.                         ,@level0name
  12803.                         ,@level1type
  12804.                         ,@level1name
  12805.                         ,@level2type
  12806.                         ,@level2name
  12807.                         ,@id            OUTPUT
  12808.                         ,@smallid        OUTPUT
  12809.                         ,@type            OUTPUT
  12810.                         ,@exists        OUTPUT
  12811.                         ,@fullname        OUTPUT
  12812.                         ,@objname        OUTPUT
  12813.  
  12814.     if @ret = 2
  12815.         raiserror(15600,-1,-1,'sp_addextendedproperty')
  12816.     if @ret <> 0
  12817.         return (1)
  12818.  
  12819.     if ( @exists = 1 ) --Indicates property for object does exist
  12820.     begin
  12821.         raiserror(15233,-1,-1,@name, @fullname)
  12822.         return(1)
  12823.     end
  12824.  
  12825.     BEGIN TRANSACTION
  12826.  
  12827.         if @objname is not null
  12828.             DBCC LockObjectSchema(@objname)
  12829.  
  12830.         insert into sysproperties (type, id, smallid, name, value)
  12831.         values (@type, @id, @smallid, @name, @value)
  12832.  
  12833.     COMMIT TRANSACTION
  12834.  
  12835.     return(0)
  12836. go
  12837.  
  12838.  
  12839. raiserror(15339,-1,-1,'sp_updateextendedproperty')
  12840. go
  12841. create procedure sp_updateextendedproperty
  12842.     @name sysname,
  12843.     @value sql_variant            = NULL,
  12844.     @level0type    varchar(128)    = NULL,
  12845.     @level0name    sysname            = NULL,
  12846.     @level1type    varchar(128)    = NULL,
  12847.     @level1name    sysname            = NULL,
  12848.     @level2type    varchar(128)    = NULL,
  12849.     @level2name    sysname            = NULL
  12850. as
  12851.  
  12852.     declare @id int
  12853.         ,@smallid smallint
  12854.         ,@type tinyint
  12855.         ,@ret int
  12856.         ,@exists int
  12857.         ,@fullname nvarchar(400)
  12858.         ,@objname        nvarchar(517)
  12859.  
  12860.     if datalength(@value) > 7500
  12861.     begin
  12862.         raiserror(15097,-1,-1)
  12863.         return 1
  12864.     end
  12865.  
  12866.     execute @ret = sp_validatepropertyinputs
  12867.                         @name
  12868.                         ,@level0type
  12869.                         ,@level0name
  12870.                         ,@level1type
  12871.                         ,@level1name
  12872.                         ,@level2type
  12873.                         ,@level2name
  12874.                         ,@id            OUTPUT
  12875.                         ,@smallid        OUTPUT
  12876.                         ,@type            OUTPUT
  12877.                         ,@exists        OUTPUT
  12878.                         ,@fullname        OUTPUT
  12879.                         ,@objname        OUTPUT
  12880.  
  12881.     if @ret = 2
  12882.         raiserror(15600,-1,-1,'sp_updateextendedproperty')
  12883.     if @ret <> 0
  12884.         return (1)
  12885.  
  12886.     if ( @exists = 0 ) --Indicates property for object does not exist
  12887.     begin
  12888.         raiserror(15217,-1,-1,@name,@fullname)
  12889.         return(1)
  12890.     end
  12891.  
  12892.     BEGIN TRANSACTION
  12893.  
  12894.         if @objname is not null
  12895.             DBCC LockObjectSchema(@objname)
  12896.  
  12897.         update sysproperties set value = @value
  12898.         where        @type = type and
  12899.                     @id =    id    and
  12900.                     @smallid =    smallid    and
  12901.                     @name = name
  12902.  
  12903.     COMMIT TRANSACTION
  12904.  
  12905.     return(0)
  12906. go
  12907.  
  12908.  
  12909. raiserror(15339,-1,-1,'sp_dropextendedproperty')
  12910. go
  12911. create procedure sp_dropextendedproperty
  12912.     @name sysname,
  12913.     @level0type    varchar(128)    = NULL,
  12914.     @level0name    sysname            = NULL,
  12915.     @level1type    varchar(128)    = NULL,
  12916.     @level1name    sysname            = NULL,
  12917.     @level2type    varchar(128)    = NULL,
  12918.     @level2name    sysname            = NULL
  12919. as
  12920.  
  12921.     declare @id int
  12922.         ,@smallid smallint
  12923.         ,@type int
  12924.         ,@ret int
  12925.         ,@exists int
  12926.         ,@fullname nvarchar(400)
  12927.         ,@objname        nvarchar(517)
  12928.  
  12929.     execute @ret = sp_validatepropertyinputs
  12930.                         @name
  12931.                         ,@level0type
  12932.                         ,@level0name
  12933.                         ,@level1type
  12934.                         ,@level1name
  12935.                         ,@level2type
  12936.                         ,@level2name
  12937.                         ,@id            OUTPUT
  12938.                         ,@smallid        OUTPUT
  12939.                         ,@type            OUTPUT
  12940.                         ,@exists        OUTPUT
  12941.                         ,@fullname        OUTPUT
  12942.                         ,@objname        OUTPUT
  12943.  
  12944.     if @ret = 2
  12945.         raiserror(15600,-1,-1,'sp_dropextendedproperty')
  12946.     if @ret <> 0
  12947.         return (1)
  12948.  
  12949.     if (@exists = 0) --Indicates property for object does not exist
  12950.     begin
  12951.         raiserror(15217,-1,-1,@name,@fullname)
  12952.         return (1)
  12953.     end
  12954.  
  12955.     BEGIN TRANSACTION
  12956.  
  12957.         if @objname is not null
  12958.             DBCC LockObjectSchema(@objname)
  12959.  
  12960.           delete from sysproperties
  12961.         where    @type = type and
  12962.                 @id =    id    and
  12963.                 @smallid =    smallid    and
  12964.                 @name = name
  12965.  
  12966.     COMMIT TRANSACTION
  12967.  
  12968.     return(0)
  12969. go
  12970.  
  12971.  
  12972. /******************************************************************************
  12973. *************************  LOGIN-SECURITY (LOCAL)  ****************************
  12974. ******************************************************************************/
  12975. checkpoint
  12976. go
  12977. if object_id('sp_addlogin','P') IS NOT NULL
  12978.     drop procedure sp_addlogin
  12979. if object_id('sp_password','P') IS NOT NULL
  12980.     drop procedure sp_password
  12981. if object_id('sp_droplogin','P') IS NOT NULL
  12982.     drop procedure sp_droplogin
  12983. if object_id('sp_MSaddlogin_implicit_ntlogin','P') IS NOT NULL
  12984.     drop procedure sp_MSaddlogin_implicit_ntlogin
  12985. if object_id('sp_grantlogin','P') IS NOT NULL
  12986.     drop procedure sp_grantlogin
  12987. if object_id('xp_grantlogin','P') IS NOT NULL
  12988.     drop procedure xp_grantlogin
  12989. if object_id('sp_validatelogins','P') IS NOT NULL
  12990.     drop procedure sp_validatelogins
  12991. if object_id('sp_denylogin','P') IS NOT NULL
  12992.     drop procedure sp_denylogin
  12993. if object_id('sp_revokelogin','P') IS NOT NULL
  12994.     drop procedure sp_revokelogin
  12995. if object_id('xp_revokelogin','P') IS NOT NULL
  12996.     drop procedure xp_revokelogin
  12997. if object_id('sp_defaultdb','P') IS NOT NULL
  12998.     drop procedure sp_defaultdb
  12999. if object_id('sp_defaultlanguage','P') IS NOT NULL
  13000.     drop procedure sp_defaultlanguage
  13001. if object_id('sp_addsrvrolemember','P') IS NOT NULL
  13002.     drop procedure sp_addsrvrolemember
  13003. if object_id('sp_dropsrvrolemember','P') IS NOT NULL
  13004.     drop procedure sp_dropsrvrolemember
  13005. go
  13006.  
  13007. ------------------------------- sp_addlogin -----------------------------------
  13008.  
  13009. raiserror(15339,-1,-1,'sp_addlogin')
  13010. go
  13011. create procedure sp_addlogin
  13012.     @loginame        sysname
  13013.    ,@passwd         sysname = Null
  13014.    ,@defdb          sysname = 'master'      -- UNDONE: DEFAULT CONFIGURABLE???
  13015.    ,@deflanguage    sysname = Null
  13016.    ,@sid            varbinary(16) = Null
  13017.    ,@encryptopt        varchar(20) = Null
  13018. AS
  13019.     -- SETUP RUNTIME OPTIONS / DECLARE VARIABLES --
  13020.     set nocount on
  13021.     Declare @ret    int    -- return value of sp call
  13022.  
  13023.     -- CHECK PERMISSIONS --
  13024.     IF (not is_srvrolemember('securityadmin') = 1)
  13025.     begin
  13026.        dbcc auditevent (104, 1, 0, @loginame, NULL, NULL, @sid)
  13027.        raiserror(15247,-1,-1)
  13028.        return (1)
  13029.     end
  13030.     ELSE
  13031.     begin
  13032.        dbcc auditevent (104, 1, 1, @loginame, NULL, NULL, @sid)
  13033.     end
  13034.  
  13035.     -- DISALLOW USER TRANSACTION --
  13036.     set implicit_transactions off
  13037.     IF (@@trancount > 0)
  13038.     begin
  13039.         raiserror(15002,-1,-1,'sp_addlogin')
  13040.         return (1)
  13041.     end
  13042.  
  13043.     -- VALIDATE LOGIN NAME AS:
  13044.     --  (1) Valid SQL Name (SQL LOGIN)
  13045.     --  (2) No backslash (NT users only)
  13046.     --  (3) Not a reserved login name
  13047.     execute @ret = sp_validname @loginame
  13048.     if (@ret <> 0)
  13049.         return (1)
  13050.     if (charindex('\', @loginame) > 0)
  13051.     begin
  13052.         raiserror(15006,-1,-1,@loginame)
  13053.         return (1)
  13054.     end
  13055.  
  13056.     --Note: different case sa is allowed.
  13057.     if (@loginame = 'sa' or lower(@loginame) in ('public'))
  13058.     begin
  13059.         raiserror(15405, -1 ,-1, @loginame)
  13060.         return (1)
  13061.     end
  13062.  
  13063.     -- LOGIN NAME MUST NOT ALREADY EXIST --
  13064.     if exists(select * from master.dbo.syslogins where loginname = @loginame)
  13065.     begin
  13066.         raiserror(15025,-1,-1,@loginame)
  13067.         return (1)
  13068.     end
  13069.  
  13070.     -- VALIDATE DEFAULT DATABASE --
  13071.     IF db_id(@defdb) IS NULL
  13072.     begin
  13073.         raiserror(15010,-1,-1,@defdb)
  13074.         return (1)
  13075.     end
  13076.  
  13077.     -- VALIDATE DEFAULT LANGUAGE --
  13078.     IF (@deflanguage IS NOT Null)
  13079.     begin
  13080.         Execute @ret = sp_validlang @deflanguage
  13081.         IF (@ret <> 0)
  13082.             return (1)
  13083.     end
  13084.     ELSE
  13085.     begin
  13086.         select @deflanguage = name from master.dbo.syslanguages
  13087.         where langid = @@default_langid    --server default language
  13088.  
  13089.         if @deflanguage is null
  13090.             select @deflanguage = N'us_english'
  13091.     end
  13092.  
  13093.     -- VALIDATE SID IF GIVEN --
  13094.     if ((@sid IS NOT Null) and (datalength(@sid) <> 16))
  13095.     begin
  13096.         raiserror(15419,-1,-1)
  13097.          return (1)
  13098.     end
  13099.     else if @sid is null
  13100.         select @sid = newid()
  13101.     if (suser_sname(@sid) IS NOT Null)
  13102.     begin
  13103.         raiserror(15433,-1,-1)
  13104.          return (1)
  13105.     end
  13106.  
  13107.     -- VALIDATE AND USE ENCRYPTION OPTION --
  13108.     declare @xstatus smallint
  13109.     select @xstatus = 2    -- access
  13110.     if @encryptopt is null
  13111.         select @passwd = pwdencrypt(@passwd)
  13112.     else if @encryptopt = 'skip_encryption_old'
  13113.     begin
  13114.         select @xstatus = @xstatus | 0x800,    -- old-style encryption
  13115.             @passwd = convert(sysname, convert(varbinary(30), convert(varchar(30), @passwd)))
  13116.     end
  13117.     else if @encryptopt <> 'skip_encryption'
  13118.     begin
  13119.         raiserror(15600,-1,-1,'sp_addlogin')
  13120.         return 1
  13121.     end
  13122.  
  13123.     -- ATTEMPT THE INSERT OF THE NEW LOGIN --
  13124.     INSERT INTO master.dbo.sysxlogins VALUES
  13125.         (NULL, @sid, @xstatus, getdate(),
  13126.             getdate(), @loginame, convert(varbinary(256), @passwd),
  13127.             db_id(@defdb), @deflanguage)
  13128.     if @@error <> 0        -- this indicates we saw duplicate row
  13129.         return (1)
  13130.  
  13131.     -- UPDATE PROTECTION TIMESTAMP FOR MASTER DB, TO INDICATE SYSLOGINS CHANGE --
  13132.     exec('use master grant all to null')
  13133.  
  13134.     -- FINALIZATION: RETURN SUCCESS/FAILURE --
  13135.     raiserror(15298,-1,-1)
  13136.     return  (0)    -- sp_addlogin
  13137. go
  13138.  
  13139. ------------------------------- sp_password -----------------------------------
  13140.  
  13141. raiserror(15339,-1,-1,'sp_password')
  13142. go
  13143. create procedure sp_password
  13144.     @old sysname = NULL,        -- the old (current) password
  13145.     @new sysname,               -- the new password
  13146.     @loginame sysname = NULL    -- user to change password on
  13147. as
  13148.     -- SETUP RUNTIME OPTIONS / DECLARE VARIABLES --
  13149.     set nocount on
  13150.     declare @self int
  13151.     select @self = CASE WHEN @loginame is null THEN 1 ELSE 2 END
  13152.  
  13153.     -- RESOLVE LOGIN NAME
  13154.     if @loginame is null
  13155.         select @loginame = suser_sname()
  13156.  
  13157.     -- CHECK PERMISSIONS (SecurityAdmin per Richard Waymire) --
  13158.     IF (not is_srvrolemember('securityadmin') = 1)
  13159.         AND not @self = 1
  13160.     begin
  13161.        dbcc auditevent (107, @self, 0, @loginame, NULL, NULL, NULL)
  13162.        raiserror(15210,-1,-1)
  13163.        return (1)
  13164.     end
  13165.     ELSE
  13166.     begin
  13167.        dbcc auditevent (107, @self, 1, @loginame, NULL, NULL, NULL)
  13168.     end
  13169.  
  13170.     -- DISALLOW USER TRANSACTION --
  13171.     set implicit_transactions off
  13172.     IF (@@trancount > 0)
  13173.     begin
  13174.         raiserror(15002,-1,-1,'sp_password')
  13175.         return (1)
  13176.     end
  13177.  
  13178.     -- RESOLVE LOGIN NAME (disallows nt names)
  13179.     if not exists (select * from master.dbo.syslogins where
  13180.                     loginname = @loginame and isntname = 0)
  13181.     begin
  13182.         raiserror(15007,-1,-1,@loginame)
  13183.         return (1)
  13184.     end
  13185.  
  13186.     -- IF non-SYSADMIN ATTEMPTING CHANGE TO SYSADMIN, REQUIRE PASSWORD (218078) --
  13187.     if (@self <> 1 AND is_srvrolemember('sysadmin') = 0 AND exists
  13188.             (SELECT * FROM master.dbo.syslogins WHERE loginname = @loginame and isntname = 0
  13189.                 AND sysadmin = 1) )
  13190.         SELECT @self = 1
  13191.  
  13192.     -- CHECK OLD PASSWORD IF NEEDED --
  13193.     if (@self = 1 or @old is not null)
  13194.         if not exists (select * from master.dbo.sysxlogins
  13195.                         where srvid IS NULL and
  13196.                               name = @loginame and
  13197.                               ( (@old is null and password is null) or
  13198.                               (pwdcompare(@old, password, (CASE WHEN xstatus&2048 = 2048 THEN 1 ELSE 0 END)) = 1) )   )
  13199.         begin
  13200.             raiserror(15211,-1,-1)
  13201.             return (1)
  13202.         end
  13203.  
  13204.     -- CHANGE THE PASSWORD --
  13205.     update master.dbo.sysxlogins
  13206.     set password = convert(varbinary(256), pwdencrypt(@new)), xdate2 = getdate(), xstatus = xstatus & (~2048)
  13207.     where name = @loginame and srvid IS NULL
  13208.  
  13209.     -- UPDATE PROTECTION TIMESTAMP FOR MASTER DB, TO INDICATE SYSLOGINS CHANGE --
  13210.     exec('use master grant all to null')
  13211.  
  13212.     -- FINALIZATION: RETURN SUCCESS/FAILURE --
  13213.     if @@error <> 0
  13214.         return (1)
  13215.     raiserror(15478,-1,-1)
  13216.     return  (0)    -- sp_password
  13217. go
  13218.  
  13219. checkpoint
  13220. go
  13221. ------------------------------- sp_droplogin ----------------------------------
  13222.  
  13223. raiserror(15339,-1,-1,'sp_droplogin')
  13224. go
  13225. create procedure sp_droplogin
  13226.     @loginame sysname
  13227. as
  13228.  
  13229. declare @exec_stmt nvarchar(890)
  13230.  
  13231.     -- SETUP RUNTIME OPTIONS / DECLARE VARIABLES --
  13232.     set nocount on
  13233.     declare    @sid    varbinary(85)
  13234.  
  13235.     /*Create temp tables before any DML to ensure dynamic*/
  13236.     -- CREATE TEMPORARY TABLES FOR LATER USE --
  13237.        create table #db_list (dbname sysname collate database_default not null, user_name sysname collate database_default not null)
  13238.     create table #retval (job_count int not null)
  13239.  
  13240.     -- CHECK PERMISSIONS --
  13241.     IF (not is_srvrolemember('securityadmin') = 1)
  13242.     begin
  13243.        dbcc auditevent (104, 2, 0, @loginame, NULL, NULL, NULL)
  13244.        raiserror(15247,-1,-1)
  13245.        return (1)
  13246.     end
  13247.     ELSE
  13248.     begin
  13249.        dbcc auditevent (104, 2, 1, @loginame, NULL, NULL, NULL)
  13250.     end
  13251.  
  13252.     -- DISALLOW USER TRANSACTION --
  13253.     set implicit_transactions off
  13254.     IF (@@trancount > 0)
  13255.     begin
  13256.         raiserror(15002,-1,-1,'sp_droplogin')
  13257.         return (1)
  13258.     end
  13259.  
  13260.     -- VALIDATE LOGIN NAME (SQL LOGIN) --
  13261.     select @sid = sid from master.dbo.syslogins
  13262.         where loginname = @loginame and isntname = 0
  13263.     if (@sid is null)
  13264.     begin
  13265.         raiserror(15007,10,-1,@loginame)
  13266.         return(1)
  13267.     end
  13268.     -- CANNOT CHANGE SA ROLES --
  13269.     else if @sid = 0x1    -- 'sa'
  13270.     begin
  13271.         raiserror(15405, -1 ,-1, @loginame)
  13272.         return (1)
  13273.     end
  13274.  
  13275.     -- CHECK IF @sid IS CURRENTLY LOGGED IN (ignore cached remote connections) --
  13276.     if exists(select * from master.dbo.sysprocesses where sid = @sid and status != 'dormant')
  13277.     begin
  13278.         raiserror(15434, -1, -1, @loginame)
  13279.         return(1)
  13280.     end
  13281.  
  13282.     -- CHECK IF ANY DATABASES ARE OWNED BY LOGIN --
  13283.     if exists(select * from master.dbo.sysdatabases where sid = @sid)
  13284.     begin
  13285.         raiserror(15174, -1, -1, @loginame)
  13286.         select 'Databases owned by login:' = name
  13287.                 from master.dbo.sysdatabases where sid = @sid
  13288.         return(1)
  13289.     end
  13290.  
  13291.     -- COLLECT ALL INSTANCES OF USE OF THIS LOGIN IN SYSUSERS --
  13292.     declare @dbname        sysname
  13293.     declare ms_crs_dbname cursor local keyset for select name from master.dbo.sysdatabases
  13294.     open ms_crs_dbname
  13295.     fetch ms_crs_dbname into @dbname
  13296.     while @@fetch_status >= 0
  13297.     begin
  13298.         if (has_dbaccess(@dbname) = 1)
  13299.         begin
  13300.             select @exec_stmt = 'use ' + quotename( @dbname , '[') + '
  13301.                    insert into #db_list (dbname, user_name)
  13302.                 select N'+ quotename( @dbname , '''')+', name from sysusers
  13303.                 where sid = suser_sid(N' + quotename( @loginame , '''') + ') '
  13304.             exec (@exec_stmt)
  13305.         end
  13306.         else
  13307.             raiserror(15622,-1,-1, @dbname)
  13308.  
  13309.         fetch ms_crs_dbname into @dbname
  13310.     end
  13311.     deallocate ms_crs_dbname
  13312.  
  13313.     -- ERROR IF LOGIN USED AS USER IN ANY DATABASE --
  13314.     if (select count(*) from #db_list) <> 0
  13315.     begin
  13316.         raiserror(15175,-1,-1,@loginame)
  13317.         select
  13318.             'Database name:' = dbname,
  13319.             'User name:' = user_name,
  13320.             'Mapping type:' = 'user'
  13321.         from #db_list
  13322.         order by dbname
  13323.         return (1)
  13324.     end
  13325.  
  13326.     -- VERIFY NO JOBS IN MSDB OWNED BY THIS LOGIN --
  13327.     if db_id('msdb') is not null
  13328.         and object_id('msdb.dbo.sp_check_for_owned_jobs') is not null
  13329.     begin
  13330.         exec msdb.dbo.sp_check_for_owned_jobs @loginame, '#retval'
  13331.         if exists (select job_count from #retval where job_count > 0)
  13332.         begin
  13333.             declare @job_count int
  13334.             select @job_count = job_count from #retval
  13335.             raiserror(14248, -1, -1, @job_count)
  13336.             return (1)
  13337.         end
  13338.     end
  13339.  
  13340.     -- DELETE THIS LOGIN (ALSO DELETES REMOTE LOGINS MAPPED TO IT) --
  13341.     delete from master.dbo.sysxlogins where sid = @sid
  13342.  
  13343.     -- FINALIZATION: SUCCESS/FAILURE MESSAGE
  13344.     if @@rowcount > 0
  13345.     begin
  13346.         -- UPDATE PROTECTION TIMESTAMP FOR MASTER DB, TO INDICATE SYSLOGINS CHANGE --
  13347.         exec('use master grant all to null')
  13348.  
  13349.         raiserror(15479,-1,-1)
  13350.         return (0)
  13351.     end
  13352.     else
  13353.     begin
  13354.         raiserror(15007,10,-1,@loginame)
  13355.         return (1)
  13356.     end     -- sp_droplogin
  13357. go
  13358.  
  13359. ----------------------- sp_MSaddlogin_implicit_ntlogin ------------------------
  13360.  
  13361. raiserror(15339,-1,-1,'sp_MSaddlogin_implicit_ntlogin')
  13362. go
  13363. ----------------------------------------
  13364. -- NOTE: FOR INTERNAL SECURITY USE ONLY!
  13365. --      DO NOT DOCUMENT OR USE!
  13366. ----------------------------------------
  13367. create procedure sp_MSaddlogin_implicit_ntlogin
  13368.     @loginame        sysname
  13369. AS
  13370.  
  13371. declare @default_lang sysname
  13372.  
  13373.     -- NO-OP IF LOGIN ALREADY EXISTS --
  13374.     -- if suser_sid(@loginame) is null
  13375.  
  13376.     if not exists(select * from master.dbo.syslogins where loginname = @loginame)
  13377.     begin
  13378.  
  13379.         -- MUST BE NT NAME --
  13380.         if (charindex('\', @loginame) = 0)
  13381.             return (1)
  13382.  
  13383.         declare    @newsid    varbinary(85),
  13384.                 @status smallint
  13385.  
  13386.         -- OBTAIN NT SID FOR THIS LOGIN (SET STATUS BITS) --
  13387.         select @status = 4      -- ntlogin(4)
  13388.         select @newsid = get_sid('\U'+@loginame, NULL)        -- NT user
  13389.         if (@newsid IS Null)
  13390.         begin
  13391.             select @newsid = get_sid('\G'+@loginame, NULL)  -- NT group
  13392.             IF (@newsid IS Null)
  13393.                 return (1)
  13394.         end
  13395.         else
  13396.             select @status = @status | 8    -- NTUser
  13397.         
  13398.         -- FAIL IF SID ALREADY IN SYSLOGINS 
  13399.         if exists(select * from master.dbo.syslogins where sid = @newsid)
  13400.             return (1)
  13401.  
  13402.         select @default_lang = name from master.dbo.syslanguages
  13403.         where langid = @@default_langid     --server default language
  13404.  
  13405.  
  13406.         -- ADD IMPLICIT LOGIN ENTRY --
  13407.         INSERT into master.dbo.sysxlogins Values
  13408.             (NULL, @newsid, @status, getdate(), getdate(),
  13409.                 @loginame, NULL, 1, isnull(@default_lang, N'us_english'))
  13410.         if @@error <> 0        -- this indicates we saw duplicate row
  13411.             return @@error
  13412.  
  13413.         -- UPDATE PROTECTION TIMESTAMP FOR MASTER DB, TO INDICATE SYSLOGINS CHANGE --
  13414.         exec('use master grant all to null')
  13415.  
  13416.     end
  13417.  
  13418.     -- RETURN FAILURE/SUCCESS
  13419.     return (0) -- sp_MSaddlogin_implicit_ntlogin
  13420. go
  13421.  
  13422. ------------------------------- sp_grantlogin ---------------------------------
  13423.  
  13424. raiserror(15339,-1,-1,'sp_grantlogin')
  13425. go
  13426. create procedure sp_grantlogin
  13427.     @loginame        sysname
  13428. AS
  13429.     -- SETUP RUNTIME OPTIONS / DECLARE VARIABLES --
  13430.     set nocount on
  13431.     declare @ret   int    -- return value of sp call
  13432.  
  13433.     -- CHECK PERMISSIONS --
  13434.     IF (not is_srvrolemember('securityadmin') = 1)
  13435.     begin
  13436.        dbcc auditevent (105, 1, 0, @loginame, NULL, NULL, NULL)
  13437.        raiserror(15247,-1,-1)
  13438.        return (1)
  13439.     end
  13440.     ELSE
  13441.     begin
  13442.        dbcc auditevent (105, 1, 1, @loginame, NULL, NULL, NULL)
  13443.     end
  13444.  
  13445.     -- DISALLOW USER TRANSACTION --
  13446.     set implicit_transactions off
  13447.     IF (@@trancount > 0)
  13448.     begin
  13449.         raiserror(15002,-1,-1,'sp_grantlogin')
  13450.         return (1)
  13451.     end
  13452.  
  13453.     -- DISALLOW SQL LOGIN (IE. MUST BE 'DOMAIN\USER') --
  13454.     if (charindex('\', @loginame) = 0)
  13455.     begin
  13456.         raiserror(15407, -1, -1, @loginame)
  13457.         return (1)
  13458.     end
  13459.  
  13460.     -- ADD ROW FOR NT LOGIN IF NEEDED --
  13461.     if not exists(select * from master.dbo.syslogins where loginname = @loginame)
  13462.     begin
  13463.         execute @ret = sp_MSaddlogin_implicit_ntlogin @loginame
  13464.         if (@ret <> 0)
  13465.         begin
  13466.             raiserror(15401,-1,-1 ,@loginame)
  13467.             return (1)
  13468.         end
  13469.     end
  13470.  
  13471.     -- UPDATE LOGIN BITS --
  13472.     update master.dbo.sysxlogins set xstatus = (xstatus & ~1) | 2, xdate2 = getdate()
  13473.         where name = @loginame and srvid IS NULL
  13474.  
  13475.     -- UPDATE PROTECTION TIMESTAMP FOR MASTER DB, TO INDICATE SYSLOGINS CHANGE --
  13476.     exec('use master grant all to null')
  13477.  
  13478.     -- FINALIZATION: RETURN SUCCESS/FAILURE
  13479.     if @@error <> 0
  13480.     begin
  13481.         raiserror(15480,-1,-1,@loginame)
  13482.         return (1)
  13483.     end
  13484.     else
  13485.     begin
  13486.         raiserror(15481,-1,-1,@loginame)
  13487.         return (0)
  13488.     end -- sp_grantlogin
  13489. go
  13490.  
  13491. ------------------------------- sp_validatelogins ---------------------------------
  13492.  
  13493. raiserror(15339,-1,-1,'sp_validatelogins')
  13494. go
  13495. create proc sp_validatelogins
  13496. AS
  13497.     -- Must be securityadmin (or sysadmin) to execute
  13498.     if is_srvrolemember('securityadmin') = 0 and is_srvrolemember('sysadmin') = 0
  13499.     begin
  13500.         raiserror(15247,-1,-1)
  13501.         return 1
  13502.     end
  13503.  
  13504.     -- Use get_sid() to determine if nt name is still valid (builtin is only available from system procs!)
  13505.     select 'SID' = sid, 'NT Login' = loginname from master.dbo.syslogins
  13506.         where isntname = 1 and get_sid(loginname, NULL) is null
  13507.     return 0 -- sp_validatelogins
  13508. go
  13509.  
  13510. -- FOR BACKWARD COMPATIBILTY ONLY --
  13511. raiserror(15339,-1,-1,'xp_grantlogin')
  13512. go
  13513. create procedure xp_grantlogin
  13514.     @loginame       sysname,
  13515.     @logintype      varchar(5) = Null       -- ignored unless 'admin'
  13516. AS
  13517.     set nocount on
  13518.  
  13519.     -- IF NAME NOT 'DOMAIN\USER', ADD DEFAULT DOMAIN --
  13520.     if (charindex('\', @loginame) = 0)
  13521.     begin
  13522.         declare @defdom varchar(25)
  13523.         exec master.dbo.xp_instance_regread 'HKEY_LOCAL_MACHINE',
  13524.                 'SOFTWARE\Microsoft\MSSQLServer\MSSQLServer',
  13525.                 'DefaultDomain', @defdom out
  13526.         select @loginame = @defdom + '\' + @loginame
  13527.     end
  13528.  
  13529.     Declare @ret   int     -- return value of sp call
  13530.     execute @ret = sp_grantlogin @loginame
  13531.     if (@ret = 0 and @logintype = 'admin')
  13532.         execute @ret = sp_addsrvrolemember @loginame, 'sysadmin'
  13533.     return (@ret)
  13534. go
  13535.  
  13536. checkpoint
  13537. go
  13538. ------------------------------- sp_denylogin ----------------------------------
  13539.  
  13540. raiserror(15339,-1,-1,'sp_denylogin')
  13541. go
  13542. create procedure sp_denylogin
  13543.     @loginame        sysname
  13544. AS
  13545.     -- SETUP RUNTIME OPTIONS / DECLARE VARIABLES --
  13546.     set nocount on
  13547.     declare @ret   int    -- return value of sp call
  13548.  
  13549.     -- CHECK PERMISSIONS --
  13550.     IF (not is_srvrolemember('securityadmin') = 1)
  13551.     begin
  13552.        dbcc auditevent (105, 3, 0, @loginame, NULL, NULL, NULL)
  13553.        raiserror(15247,-1, -1)
  13554.        return (1)
  13555.     end
  13556.     ELSE
  13557.     begin
  13558.        dbcc auditevent (105, 3, 1, @loginame, NULL, NULL, NULL)
  13559.     end
  13560.  
  13561.     -- DISALLOW USER TRANSACTION --
  13562.     set implicit_transactions off
  13563.     IF (@@trancount > 0)
  13564.     begin
  13565.         raiserror(15002,-1,-1,'sp_denylogin')
  13566.         return (1)
  13567.     end
  13568.  
  13569.     -- DISALLOW SQL LOGIN (IE. MUST BE 'DOMAIN\USER') --
  13570.     if (charindex('\', @loginame) = 0)
  13571.     begin
  13572.         raiserror(15407, -1, -1, @loginame)
  13573.         return (1)
  13574.     end
  13575.  
  13576.     -- ADD ROW FOR NT LOGIN IF NEEDED --
  13577.     if not exists(select * from master.dbo.syslogins where loginname = @loginame)
  13578.     begin
  13579.         execute @ret = sp_MSaddlogin_implicit_ntlogin @loginame
  13580.         if (@ret <> 0)
  13581.         begin
  13582.             raiserror(15401,-1,-1 ,@loginame)
  13583.             return (1)
  13584.         end
  13585.     end
  13586.  
  13587.     -- UPDATE LOGIN BITS --
  13588.     update master.dbo.sysxlogins set xstatus = (xstatus & ~2) | 1, xdate2 = getdate()
  13589.         where name = @loginame and srvid IS NULL
  13590.  
  13591.     -- UPDATE PROTECTION TIMESTAMP FOR MASTER DB, TO INDICATE SYSLOGINS CHANGE --
  13592.     exec('use master grant all to null')
  13593.  
  13594.     -- FINALIZATION: RETURN SUCCESS/FAILURE
  13595.     if @@error <> 0
  13596.     begin
  13597.         raiserror(15482,-1,-1,@loginame)
  13598.         return (1)
  13599.     end
  13600.     else
  13601.     begin
  13602.         raiserror(15483,-1,-1,@loginame)
  13603.         return (0)
  13604.     end -- sp_denylogin
  13605. go
  13606.  
  13607. ------------------------------- sp_revokelogin --------------------------------
  13608.  
  13609. raiserror(15339,-1,-1,'sp_revokelogin')
  13610. go
  13611. create procedure sp_revokelogin
  13612.     @loginame        sysname
  13613. AS
  13614.     -- SETUP RUNTIME OPTIONS / DECLARE VARIABLES --
  13615.     set nocount on
  13616.     declare    @sid    varbinary(85)
  13617.  
  13618.     -- CHECK PERMISSIONS --
  13619.     IF (not is_srvrolemember('securityadmin') = 1)
  13620.     begin
  13621.        dbcc auditevent (105, 2, 0, @loginame, NULL, NULL, NULL)
  13622.        raiserror(15247,-1,-1)
  13623.        return (1)
  13624.     end
  13625.     ELSE
  13626.     begin
  13627.        dbcc auditevent (105, 2, 1, @loginame, NULL, NULL, NULL)
  13628.     end
  13629.  
  13630.     -- DISALLOW USER TRANSACTION --
  13631.     set implicit_transactions off
  13632.     IF (@@trancount > 0)
  13633.     begin
  13634.         raiserror(15002,-1,-1,'sp_revokelogin')
  13635.         return (1)
  13636.     end
  13637.  
  13638.     -- DISALLOW SQL LOGIN (IE. MUST BE 'DOMAIN\USER') --
  13639.     if (charindex('\', @loginame) = 0)
  13640.     begin
  13641.         raiserror(15407, -1, -1, @loginame)
  13642.         return (1)
  13643.     end
  13644.  
  13645.     -- REMOVE ROW IF EXISTS FOR LOGIN PROVIDED IT IS AN NT NAME --
  13646.     -- select @sid = suser_sid(@loginame)
  13647.     -- if @sid is not null
  13648.     if exists(select * from master.dbo.syslogins where loginname = @loginame and isntname = 1)
  13649.     begin
  13650.         select @sid = sid from master.dbo.syslogins where loginname = @loginame and isntname = 1
  13651.  
  13652.         -- For nt logins, skip sid foreign-key checks. --
  13653.         -- also deletes remote logins mapped to this user --
  13654.         delete from master.dbo.sysxlogins where sid = @sid
  13655.  
  13656.         -- UPDATE PROTECTION TIMESTAMP FOR MASTER DB, TO INDICATE SYSLOGINS CHANGE --
  13657.         exec('use master grant all to null')
  13658.     end
  13659.     else
  13660.     begin
  13661.         -- CHECK IF THIS IS A VALID NT NAME BY GETTING ITS SID FROM NT
  13662.         declare    @newsid    varbinary(85)
  13663.         select @newsid = get_sid('\U'+@loginame, NULL)        -- NT user
  13664.         IF (@newsid IS Null)
  13665.         begin
  13666.             select @newsid = get_sid('\G'+@loginame, NULL)  -- NT group
  13667.             IF (@newsid IS Null)
  13668.             begin
  13669.                 raiserror(15401,-1,-1 ,@loginame)
  13670.                 return (1)
  13671.             end
  13672.         end
  13673.     end
  13674.  
  13675.  
  13676.     -- FINALIZATION: RETURN SUCCESS/FAILURE
  13677.     if @@error <> 0
  13678.     begin
  13679.         raiserror(15484,-1,-1,@loginame)
  13680.         return (1)
  13681.     end
  13682.     else
  13683.     begin
  13684.         raiserror(15485,-1,-1,@loginame)
  13685.         return (0)
  13686.     end -- sp_revokelogin
  13687. go
  13688.  
  13689.  
  13690. -- FOR BACKWARD COMPATIBILTY ONLY --
  13691. raiserror(15339,-1,-1,'xp_revokelogin')
  13692. go
  13693. create procedure xp_revokelogin
  13694.     @loginame       sysname
  13695. AS
  13696.     set nocount on
  13697.  
  13698.     -- IF NAME NOT 'DOMAIN\USER', ADD DEFAULT DOMAIN --
  13699.     if (charindex('\', @loginame) = 0)
  13700.     begin
  13701.         declare @defdom varchar(25)
  13702.         exec master.dbo.xp_instance_regread 'HKEY_LOCAL_MACHINE',
  13703.                 'SOFTWARE\Microsoft\MSSQLServer\MSSQLServer',
  13704.                 'DefaultDomain', @defdom out
  13705.         select @loginame = @defdom + '\' + @loginame
  13706.     end
  13707.  
  13708.     Declare @ret   int     -- return value of sp call
  13709.     execute @ret = sp_revokelogin @loginame
  13710.     return (@ret)
  13711. go
  13712.  
  13713. ------------------------------- sp_defaultdb ----------------------------------
  13714.  
  13715. raiserror(15339,-1,-1,'sp_defaultdb')
  13716. go
  13717. create procedure sp_defaultdb
  13718.     @loginame   sysname,    -- login name
  13719.     @defdb      sysname     -- default db
  13720. as
  13721.     -- SETUP RUNTIME OPTIONS / DECLARE VARIABLES --
  13722.     set nocount on
  13723.     declare @ret   int    -- return value of sp call
  13724.  
  13725.     -- CHECK PERMISSIONS --
  13726.     IF (not is_srvrolemember('securityadmin') = 1)
  13727.         AND not @loginame = suser_sname()
  13728.     begin
  13729.         dbcc auditevent (106, 1, 0, @loginame, NULL, NULL, NULL)
  13730.         raiserror(15132,-1,-1)
  13731.         return (1)
  13732.     end
  13733.     ELSE
  13734.     begin
  13735.        dbcc auditevent (106, 1, 1, @loginame, NULL, NULL, NULL)
  13736.     end
  13737.  
  13738.     -- DISALLOW USER TRANSACTION --
  13739.     set implicit_transactions off
  13740.     IF (@@trancount > 0)
  13741.     begin
  13742.         raiserror(15002,-1,-1,'sp_defaultdb')
  13743.         return (1)
  13744.     end
  13745.  
  13746.  
  13747.     -- VALIDATE DATABASE NAME --
  13748.     if db_id(@defdb) IS NULL
  13749.     begin
  13750.         raiserror(15010,-1,-1,@defdb)
  13751.         return (1)
  13752.     end
  13753.  
  13754.     -- ADD ROW FOR NT LOGIN IF NEEDED --
  13755.     if not exists(select * from master.dbo.syslogins where loginname = @loginame)
  13756.     begin
  13757.         execute @ret = sp_MSaddlogin_implicit_ntlogin @loginame
  13758.         if (@ret <> 0)
  13759.         begin
  13760.             raiserror(15007,-1,-1,@loginame)
  13761.             return (1)
  13762.         end
  13763.     end
  13764.  
  13765.     -- CHANGE DEFAULT DATABASE --
  13766.     update master.dbo.sysxlogins set dbid = db_id(@defdb), xdate2 = getdate()
  13767.         where name = @loginame and srvid IS NULL
  13768.  
  13769.     -- UPDATE PROTECTION TIMESTAMP FOR MASTER DB, TO INDICATE SYSLOGINS CHANGE --
  13770.     exec('use master grant all to null')
  13771.  
  13772.     -- FINALIZATION: RETURN SUCCESS/FAILURE
  13773.     IF (@@error <> 0)
  13774.         return (1)
  13775.     raiserror(15486,-1,-1)
  13776.     return (0) -- sp_defaultdb
  13777. go
  13778.  
  13779. checkpoint
  13780. go
  13781. ---------------------------- sp_defaultlanguage -------------------------------
  13782.  
  13783. raiserror(15339,-1,-1,'sp_defaultlanguage')
  13784. go
  13785. create procedure sp_defaultlanguage
  13786.     @loginame sysname,            -- login name
  13787.     @language sysname = NULL    -- default language
  13788. as
  13789.     -- SETUP RUNTIME OPTIONS / DECLARE VARIABLES --
  13790.     set nocount on
  13791.     declare @ret   int     -- return value of sp call
  13792.  
  13793.     -- CHECK PERMISSIONS --
  13794.     IF (not is_srvrolemember('securityadmin') = 1)
  13795.         AND not @loginame = suser_sname()
  13796.     begin
  13797.         dbcc auditevent (106, 2, 0, @loginame, NULL, NULL, NULL)
  13798.         raiserror(15247,-1,-1)
  13799.         return (1)
  13800.     end
  13801.     ELSE
  13802.     begin
  13803.        dbcc auditevent (106, 2, 1, @loginame, NULL, NULL, NULL)
  13804.     end
  13805.  
  13806.     -- DISALLOW USER TRANSACTION --
  13807.     set implicit_transactions off
  13808.     IF (@@trancount > 0)
  13809.     begin
  13810.         raiserror(15002,-1,-1,'sp_defaultlanguage')
  13811.         return (1)
  13812.     end
  13813.  
  13814.     -- VALIDATE LANGUAGE --
  13815.     IF (@language is not Null)
  13816.     begin
  13817.         Execute @ret = sp_validlang @language
  13818.         IF (@ret <> 0)
  13819.             return (1)
  13820.     end
  13821.     else
  13822.     begin
  13823.  
  13824.         select @language = name from master.dbo.syslanguages
  13825.         where langid = @@default_langid  --default language
  13826.  
  13827.         if @language is null
  13828.             select @language = N'us_english'
  13829.     end
  13830.  
  13831.     -- ADD ROW FOR NT LOGIN IF NEEDED --
  13832.     if not exists(select * from master.dbo.syslogins where loginname = @loginame)
  13833.     begin
  13834.         execute @ret = sp_MSaddlogin_implicit_ntlogin @loginame
  13835.         if (@ret <> 0)
  13836.         begin
  13837.             raiserror(15007,-1,-1,@loginame)
  13838.             return (1)
  13839.         end
  13840.     end
  13841.  
  13842.     -- CHANGE DEFAULT LANGUAGE --
  13843.     update master.dbo.sysxlogins set language = @language, xdate2 = getdate()
  13844.         where name = @loginame and srvid IS NULL
  13845.  
  13846.     -- UPDATE PROTECTION TIMESTAMP FOR MASTER DB, TO INDICATE SYSLOGINS CHANGE --
  13847.     exec('use master grant all to null')
  13848.  
  13849.     -- FINALIZATION: RETURN SUCCESS/FAILURE
  13850.     if @@error <> 0
  13851.         return (1)
  13852.     raiserror(15487,-1,-1,@loginame,@language)
  13853.     return (0) -- sp_defaultlanguage
  13854. go
  13855.  
  13856. --------------------------- sp_addsrvrolemember -------------------------------
  13857.  
  13858. raiserror(15339,-1,-1,'sp_addsrvrolemember')
  13859. go
  13860. create procedure sp_addsrvrolemember
  13861.     @loginame sysname,            -- login name
  13862.     @rolename sysname = NULL    -- server role name
  13863. as
  13864.     -- SETUP RUNTIME OPTIONS / DECLARE VARIABLES --
  13865.     set nocount on
  13866.     declare @ret        int,    -- return value of sp call
  13867.             @rolebit    smallint,
  13868.             @ismem      int,
  13869.             @sid        varbinary(85)
  13870.  
  13871.     -- DISALLOW USER TRANSACTION --
  13872.     set implicit_transactions off
  13873.     IF (@@trancount > 0)
  13874.     begin
  13875.         raiserror(15002,-1,-1,'sp_addsrvrolemember')
  13876.         return (1)
  13877.     end
  13878.  
  13879.     -- VALIDATE SERVER ROLE NAME, CHECKING PERMISSIONS --
  13880.     select @ismem = is_srvrolemember(@rolename)
  13881.     if @ismem is null
  13882.     begin
  13883.         dbcc auditevent (108, 1, 0, @loginame, NULL, @rolename, NULL)
  13884.         raiserror(15402, -1, -1, @rolename)
  13885.         return (1)
  13886.     end
  13887.     if @ismem = 0
  13888.     begin
  13889.         dbcc auditevent (108, 1, 0, @loginame, NULL, @rolename, NULL)
  13890.         raiserror(15247,-1,-1)
  13891.         return (1)
  13892.     end
  13893.  
  13894.     -- AUDIT A SUCCESSFUL SECURITY CHECK --
  13895.     dbcc auditevent (108, 1, 1, @loginame, NULL, @rolename, NULL)
  13896.  
  13897.     -- OBTAIN THE BIT FOR THIS ROLE --
  13898.     select @rolebit = CASE @rolename
  13899.             WHEN 'sysadmin'         THEN 16
  13900.             WHEN 'securityadmin'    THEN 32
  13901.             WHEN 'serveradmin'      THEN 64
  13902.             WHEN 'setupadmin'       THEN 128
  13903.             WHEN 'processadmin'     THEN 256
  13904.             WHEN 'diskadmin'        THEN 512
  13905.             WHEN 'dbcreator'        THEN 1024
  13906.             WHEN 'bulkadmin'        THEN 4096
  13907.             ELSE NULL END
  13908.  
  13909.     select @sid = sid from master.dbo.syslogins where loginname = @loginame
  13910.     -- ADD ROW FOR NT LOGIN IF NEEDED --
  13911.     if @sid is null
  13912.     begin
  13913.         execute @ret = sp_MSaddlogin_implicit_ntlogin @loginame
  13914.         if (@ret <> 0)
  13915.         begin
  13916.             raiserror(15007,-1,-1,@loginame)
  13917.             return (1)
  13918.         end
  13919.     end
  13920.     -- CANNOT CHANGE SA ROLES --
  13921.     else if @sid = 0x1    -- 'sa'
  13922.     begin
  13923.         raiserror(15405, -1 ,-1, @loginame)
  13924.         return (1)
  13925.     end
  13926.  
  13927.     -- UPDATE ROLE MEMBERSHIP --
  13928.     update master.dbo.sysxlogins set xstatus = xstatus | @rolebit, xdate2 = getdate()
  13929.         where name = @loginame and srvid IS NULL
  13930.  
  13931.     -- UPDATE PROTECTION TIMESTAMP FOR MASTER DB, TO INDICATE SYSLOGINS CHANGE --
  13932.     exec('use master grant all to null')
  13933.  
  13934.     raiserror(15488,-1,-1,@loginame,@rolename)
  13935.  
  13936.     -- FINALIZATION: RETURN SUCCESS/FAILURE
  13937.     return (@@error) -- sp_addsrvrolemember
  13938. go
  13939.  
  13940. checkpoint
  13941. go
  13942. --------------------------- sp_dropsrvrolemember ------------------------------
  13943.  
  13944. raiserror(15339,-1,-1,'sp_dropsrvrolemember')
  13945. go
  13946. create procedure sp_dropsrvrolemember
  13947.     @loginame sysname,            -- login name
  13948.     @rolename sysname = NULL    -- server role name
  13949. as
  13950.     -- SETUP RUNTIME OPTIONS / DECLARE VARIABLES --
  13951.     set nocount on
  13952.     declare @ret        int,    -- return value of sp call
  13953.             @rolebit    smallint,
  13954.             @ismem      int,
  13955.             @sid        varbinary(85)
  13956.  
  13957.     -- DISALLOW USER TRANSACTION --
  13958.     set implicit_transactions off
  13959.     IF (@@trancount > 0)
  13960.     begin
  13961.         raiserror(15002,-1,-1,'sp_dropsrvrolemember')
  13962.         return (1)
  13963.     end
  13964.  
  13965.     -- VALIDATE SERVER ROLE NAME, CHECKING PERMISSIONS --
  13966.     select @ismem = is_srvrolemember(@rolename)
  13967.     if @ismem is null
  13968.     begin
  13969.         dbcc auditevent (108, 2, 0, @loginame, NULL, @rolename, NULL)
  13970.         raiserror(15402, -1, -1, @rolename)
  13971.         return (1)
  13972.     end
  13973.     if @ismem = 0
  13974.     begin
  13975.         dbcc auditevent (108, 2, 0, @loginame, NULL, @rolename, NULL)
  13976.         raiserror(15247,-1,-1)
  13977.         return (1)
  13978.     end
  13979.  
  13980.     -- AUDIT THE SUCCESSFUL SECURITY CHECK --
  13981.     dbcc auditevent (108, 2, 1, @loginame, NULL, @rolename, NULL)
  13982.  
  13983.     -- OBTAIN THE BIT FOR THIS ROLE --
  13984.     select @rolebit = CASE @rolename
  13985.             WHEN 'sysadmin'         THEN 16
  13986.             WHEN 'securityadmin'    THEN 32
  13987.             WHEN 'serveradmin'      THEN 64
  13988.             WHEN 'setupadmin'       THEN 128
  13989.             WHEN 'processadmin'     THEN 256
  13990.             WHEN 'diskadmin'        THEN 512
  13991.             WHEN 'dbcreator'        THEN 1024
  13992.             WHEN 'bulkadmin'        THEN 4096
  13993.             ELSE NULL END
  13994.  
  13995.     select @sid = sid from master.dbo.syslogins where loginname = @loginame
  13996.     -- ERROR IF USER DOESNT EXIST --
  13997.     if @sid is null
  13998.     begin
  13999.         raiserror(15007,-1,-1,@loginame)
  14000.         return (1)
  14001.     end
  14002.     -- CANNOT CHANGE SA ROLES --
  14003.     else if @sid = 0x1    -- 'sa'
  14004.     begin
  14005.         raiserror(15405, -1 ,-1, @loginame)
  14006.         return (1)
  14007.     end
  14008.  
  14009.     -- UPDATE ROLE MEMBERSHIP --
  14010.     update master.dbo.sysxlogins set xstatus = xstatus & ~@rolebit, xdate2 = getdate()
  14011.         where name = @loginame and srvid IS NULL
  14012.  
  14013.     -- UPDATE PROTECTION TIMESTAMP FOR MASTER DB, TO INDICATE SYSLOGINS CHANGE --
  14014.     exec('use master grant all to null')
  14015.  
  14016.     raiserror(15489,-1,-1,@loginame,@rolename)
  14017.  
  14018.     -- FINALIZATION: RETURN SUCCESS/FAILURE
  14019.     return (@@error) -- sp_dropsrvrolemember
  14020. go
  14021.  
  14022. -- GRANT PUBLIC ACCESS (SP'S DO INTERNAL PERMISSIONS CHECKS) --
  14023. grant execute on sp_addlogin to public
  14024. grant execute on sp_password to public
  14025. grant execute on sp_droplogin to public
  14026. grant execute on sp_grantlogin to public
  14027. grant execute on sp_validatelogins to public
  14028. grant execute on xp_grantlogin to public
  14029. grant execute on sp_denylogin to public
  14030. grant execute on sp_revokelogin to public
  14031. grant execute on xp_revokelogin to public
  14032. grant execute on sp_defaultdb to public
  14033. grant execute on sp_defaultlanguage to public
  14034. grant execute on sp_addsrvrolemember to public
  14035. grant execute on sp_dropsrvrolemember to public
  14036. grant execute on sp_attach_db to public
  14037. grant execute on sp_attach_single_file_db to public
  14038. go
  14039.  
  14040. /**************************  END LOGIN-SECURITY ******************************/
  14041.  
  14042.  
  14043. /******************************************************************************
  14044. ************************  DATABASE-ACCESS-SECURITY  ***************************
  14045. ******************************************************************************/
  14046. checkpoint
  14047. go
  14048. if object_id('sp_MSadduser_implicit_ntlogin','P') IS NOT NULL
  14049.     drop procedure sp_MSadduser_implicit_ntlogin
  14050. if object_id('sp_MScheck_uid_owns_anything','P') IS NOT NULL
  14051.     drop procedure sp_MScheck_uid_owns_anything
  14052. if object_id('sp_grantdbaccess','P') IS NOT NULL
  14053.     drop procedure sp_grantdbaccess
  14054. if object_id('sp_revokedbaccess','P') IS NOT NULL
  14055.     drop procedure sp_revokedbaccess
  14056. if object_id('sp_adduser','P') IS NOT NULL
  14057.     drop procedure sp_adduser
  14058. if object_id('sp_dropuser','P') IS NOT NULL
  14059.     drop procedure sp_dropuser
  14060. if object_id('sp_addalias','P') IS NOT NULL
  14061.     drop procedure sp_addalias
  14062. if object_id('sp_dropalias','P') IS NOT NULL
  14063.     drop procedure sp_dropalias
  14064. if object_id('sp_addrole','P') IS NOT NULL
  14065.     drop procedure sp_addrole
  14066. if object_id('sp_droprole','P') IS NOT NULL
  14067.     drop procedure sp_droprole
  14068. if object_id('sp_addgroup','P') IS NOT NULL
  14069.     drop procedure sp_addgroup
  14070. if object_id('sp_dropgroup','P') IS NOT NULL
  14071.     drop procedure sp_dropgroup
  14072. if object_id('sp_addapprole','P') IS NOT NULL
  14073.     drop procedure sp_addapprole
  14074. if object_id('sp_approlepassword','P') IS NOT NULL
  14075.     drop procedure sp_approlepassword
  14076. if object_id('sp_setapprole','P') IS NOT NULL
  14077.     drop procedure sp_setapprole
  14078. if object_id('sp_dropapprole','P') IS NOT NULL
  14079.     drop procedure sp_dropapprole
  14080. if object_id('sp_addrolemember','P') IS NOT NULL
  14081.     drop procedure sp_addrolemember
  14082. if object_id('sp_droprolemember','P') IS NOT NULL
  14083.     drop procedure sp_droprolemember
  14084. if object_id('sp_changegroup','P') IS NOT NULL
  14085.     drop procedure sp_changegroup
  14086. if object_id('sp_change_users_login','P') IS NOT NULL
  14087.     drop procedure sp_change_users_login
  14088. if object_id('sp_changedbowner','P') IS NOT NULL
  14089.     drop procedure sp_changedbowner
  14090. if object_id('sp_check_removable_sysusers','P') IS NOT NULL
  14091.     drop procedure sp_check_removable_sysusers
  14092. if object_id('sp_changeobjectowner', 'P') IS NOT NULL
  14093.     drop procedure sp_changeobjectowner
  14094. go
  14095.  
  14096. ----------------------- sp_MSadduser_implicit_ntlogin -------------------------
  14097.  
  14098. raiserror(15339,-1,-1,'sp_MSadduser_implicit_ntlogin')
  14099. go
  14100. ----------------------------------------
  14101. -- NOTE: FOR INTERNAL SECURITY USE ONLY!
  14102. --      DO NOT DOCUMENT OR USE!
  14103. ----------------------------------------
  14104. create procedure sp_MSadduser_implicit_ntlogin
  14105.     @ntname         sysname
  14106. AS
  14107.     -- NO-OP IF LOGIN ALREADY EXISTS --
  14108.     if user_id(@ntname) is null
  14109.     begin
  14110.  
  14111.         -- MUST BE NT NAME --
  14112.         if (charindex('\', @ntname) = 0)
  14113.             return (1)
  14114.  
  14115.         declare    @newsid    varbinary(85),
  14116.                 @status smallint,
  14117.                 @uid    smallint
  14118.  
  14119.         -- OBTAIN NT SID FOR THIS USER (SET STATUS BITS) --
  14120.         select @status = 4      -- ntlogin(4)
  14121.         select @newsid = get_sid('\U'+@ntname, NULL)        -- NT user
  14122.         if (@newsid is Null)
  14123.         begin
  14124.             select @newsid = get_sid('\G'+@ntname, NULL)    -- NT group
  14125.             IF (@newsid IS Null)
  14126.                 return (1)
  14127.         end
  14128.         else
  14129.             select @status = @status | 8    -- NTUser
  14130.  
  14131.         -- FAIL IF SID ALREADY IN SYSUSERS --
  14132.         if exists (select sid from sysusers where sid = @newsid)
  14133.             return (1)
  14134.  
  14135.         -- OBTAIN NEW UID (RESERVE 1-4) --
  14136.         if user_name(5) IS NULL
  14137.             select @uid = 5
  14138.         else
  14139.             select @uid = min(uid)+1 from sysusers
  14140.                 where uid >= 5 and uid < (16384 - 1)    -- stay in users range
  14141.                     and user_name(uid+1) is null        -- uid not in use
  14142.         if @uid is null
  14143.         begin
  14144.             raiserror(15065,-1,-1)
  14145.             return (1)
  14146.         end
  14147.  
  14148.         -- ADD IMPLICIT SYSUSERS ENTRY --
  14149.         insert into sysusers values
  14150.             (@uid, @status, @ntname, @newsid, 0x00, getdate(), getdate(), 0, NULL)
  14151.  
  14152.         -- INVALIDATE UID CACHE FOR THIS DB --
  14153.         grant all to null
  14154.     end
  14155.  
  14156.     -- RETURN FAILURE/SUCCESS --
  14157.     return @@error -- sp_MSadduser_implicit_ntlogin
  14158. go
  14159.  
  14160. ------------------------ sp_MScheck_uid_owns_anything -------------------------
  14161.  
  14162. raiserror(15339,-1,-1,'sp_MScheck_uid_owns_anything')
  14163. go
  14164. ----------------------------------------
  14165. -- NOTE: FOR INTERNAL SECURITY USE ONLY!
  14166. --      DO NOT DOCUMENT OR USE!
  14167. ----------------------------------------
  14168. create procedure sp_MScheck_uid_owns_anything
  14169.     @uid            smallint        -- uid to for which to check ownership
  14170. as
  14171.     -- SETUP RUNTIME OPTIONS / DECLARE VARIABLES --
  14172.     set nocount on
  14173.     declare @isowner    int
  14174.     select @isowner = 0
  14175.  
  14176.     -- CHECK IF USER OWNS ANY OBJECTS --
  14177.     select @isowner = 0
  14178.     if exists (select uid from sysobjects where uid = @uid)
  14179.     begin
  14180.         raiserror(15183,-1,-1)
  14181.         select name, type from sysobjects where uid = @uid
  14182.         select @isowner = 1
  14183.     end
  14184.  
  14185.     -- CHECK IF USER OWNS ANY TYPES --
  14186.     if exists (select uid from systypes where uid = @uid)
  14187.     begin
  14188.         raiserror(15184,-1,-1)
  14189.         select user_type = name, physical_type = type_name(xtype)
  14190.                     from systypes where uid = @uid
  14191.         select @isowner = 1
  14192.     end
  14193.  
  14194.     -- CHECK IF USER GRANTED ANY PERMISSIONS --
  14195.     if exists (select grantor from syspermissions where grantor = @uid)
  14196.     begin
  14197.         raiserror(15284,-1,-1)
  14198.         select 'Grantee'=user_name(grantee) ,'Object'=object_name(id)
  14199.                     from syspermissions where grantor = @uid
  14200.         select @isowner = 1
  14201.     end
  14202.  
  14203.     -- CHECK IF USER OWNS ANY ROLES --
  14204.     if exists (select altuid from sysusers where altuid = @uid
  14205.                 and (issqlrole = 1 or isapprole = 1))
  14206.     begin
  14207.         raiserror(15421,-1,-1)
  14208.         select 'Role Name' = name,
  14209.                'Type' = CASE WHEN issqlrole=1 THEN 'SQL Role'
  14210.                              ELSE 'App Role' END
  14211.             from sysusers where altuid = @uid and (issqlrole = 1 or isapprole = 1)
  14212.         select @isowner = 1
  14213.     end
  14214.  
  14215.     return @isowner    -- sp_MScheck_uid_owns_anything
  14216. go
  14217.  
  14218. ------------------------------ sp_grantdbaccess -------------------------------
  14219.  
  14220. raiserror(15339,-1,-1,'sp_grantdbaccess')
  14221. go
  14222. create procedure sp_grantdbaccess
  14223.     @loginame       sysname,
  14224.     @name_in_db     sysname = NULL OUT
  14225. as
  14226.     -- SETUP RUNTIME OPTIONS / DECLARE VARIABLES --
  14227.     set nocount on
  14228.     declare @ret        int,    -- return value of sp call
  14229.             @uid        smallint,
  14230.             @sid        varbinary(85),
  14231.             @status     smallint
  14232.  
  14233.     if @name_in_db is null
  14234.         select @name_in_db = @loginame
  14235.  
  14236.     -- CHECK PERMISSIONS --
  14237.     if (not is_member('db_accessadmin') = 1) and
  14238.        (not is_member('db_owner') = 1)
  14239.     begin
  14240.         dbcc auditevent (109, 3, 0, @loginame, @name_in_db, NULL, NULL)
  14241.         raiserror(15247,-1,-1)
  14242.         return (1)
  14243.     end
  14244.     else
  14245.     begin
  14246.         dbcc auditevent (109, 3, 1, @loginame, @name_in_db, NULL, NULL)
  14247.     end
  14248.  
  14249.     -- DISALLOW USER TRANSACTION --
  14250.     set implicit_transactions off
  14251.     IF (@@trancount > 0)
  14252.     begin
  14253.         raiserror(15002,-1,-1,'sp_grantdbaccess')
  14254.         return (1)
  14255.     end
  14256.  
  14257.     -- VALIDATE NAME-IN-DB --
  14258.     if @name_in_db <> @loginame
  14259.     begin
  14260.         exec @ret = sp_validname @name_in_db
  14261.         if @ret <> 0
  14262.             return(1)
  14263.         if (charindex('\', @name_in_db) > 0)
  14264.         begin
  14265.             raiserror(15006,-1,-1,@name_in_db)
  14266.             return (1)
  14267.         end
  14268.     end
  14269.  
  14270.     -- CHECK FOR SPECIAL USER GUEST --
  14271.     if @name_in_db = 'guest'
  14272.     begin
  14273.         -- ERROR IF NOT USER, OR ALREADY ADDED --
  14274.         if @loginame <> 'guest'
  14275.         begin
  14276.             raiserror(15062,-1,-1)
  14277.             return(1)
  14278.         end
  14279.         if exists (select * from sysusers where hasdbaccess = 1 and name = 'guest')
  14280.         begin
  14281.             raiserror(15023,-1,-1,'guest')
  14282.             return (1)
  14283.         end
  14284.  
  14285.         -- ENABLE USER GUEST --
  14286.         update sysusers set status = (status & ~1) | 2, updatedate = getdate()
  14287.                     where name = 'guest'
  14288.         return (0)
  14289.     end
  14290.  
  14291.     -- VALIDATE LOGIN NAME (OBTAIN SID) --
  14292.     select @status = case when (charindex('\', @loginame) <> 0) then 4 else 0 end
  14293.     if @status = 0
  14294.         select @sid = sid from master.dbo.syslogins         -- sql user
  14295.             where isntname = 0 and loginname = @loginame
  14296.     if @sid is null
  14297.     begin
  14298.         -- NT GROUPS REQUIRE DOMAIN NAME --
  14299.         if @status = 4
  14300.             select @sid = get_sid('\G'+@loginame, NULL)     -- nt group
  14301.         if @sid is null
  14302.         begin
  14303.             select @sid = get_sid('\U'+@loginame, NULL)     -- nt user
  14304.             if @sid is not null
  14305.                 select @status = 12
  14306.         end
  14307.     end
  14308.     -- PREVENT USE OF CERTAIN LOGINS --
  14309.     else if @sid = 0x1    -- 'sa'
  14310.     begin
  14311.         raiserror(15405, -1, -1, @loginame)
  14312.         return (1)
  14313.     end
  14314.  
  14315.     if @sid is null
  14316.     begin
  14317.         if @status = 0
  14318.             raiserror(15007,-1,-1,@loginame)
  14319.         else
  14320.             raiserror(15401,-1,-1,@loginame)
  14321.         return (1)
  14322.     end
  14323.  
  14324.     -- CHECK IF LOGIN ALREADY IN DATABASE --
  14325.     if exists (select sid from sysusers where sid = @sid)
  14326.     begin
  14327.         -- ERROR IF LOGIN IS ALREADY ALIASED --
  14328.         if exists (select sid from sysusers where sid = @sid and isaliased = 1)
  14329.         begin
  14330.             raiserror(15022,-1,-1)
  14331.             return (1)
  14332.         end
  14333.  
  14334.         -- ERROR IF ALREADY EXISTS UNDER DIFFERENT NAME --
  14335.         if (not user_sid(user_id(@name_in_db)) = @sid)
  14336.         begin
  14337.             raiserror(15063,-1,-1)
  14338.             return (1)
  14339.         end
  14340.  
  14341.         -- ERROR IF LOGIN ALREADY HAS ACCESS --
  14342.         if exists (select sid from sysusers where sid = @sid and hasdbaccess = 1)
  14343.         begin
  14344.             if @status = 4
  14345.                 raiserror(15024,-1,-1,@name_in_db)
  14346.             else
  14347.                 raiserror(15023,-1,-1,@name_in_db)
  14348.             return (1)
  14349.         end
  14350.  
  14351.         -- GIVE DATABASE ACCESS TO THIS LOGIN --
  14352.         update sysusers set status = (status & ~1) | 2, updatedate = getdate()
  14353.                     where sid = @sid
  14354.         return @@error
  14355.     end
  14356.  
  14357.     if @name_in_db = 'sys'
  14358.         raiserror(15355,-1,-1)
  14359.  
  14360.     if user_id(@name_in_db) is not null OR
  14361.         @name_in_db IN ('system_function_schema','INFORMATION_SCHEMA')
  14362.     begin
  14363.         -- SYSUSERS NAME ALREADY EXISTS --
  14364.         if @status = 4
  14365.             raiserror(15024,-1,-1,@name_in_db)
  14366.         else
  14367.             raiserror(15023,-1,-1,@name_in_db)
  14368.         return (1)
  14369.     end
  14370.  
  14371.     -- OBTAIN NEW UID (RESERVE 1-4) --
  14372.     if user_name(5) IS NULL
  14373.         select @uid = 5
  14374.     else
  14375.         select @uid = min(uid)+1 from sysusers
  14376.             where uid >= 5 and uid < (16384 - 1)    -- stay in users range
  14377.                 and user_name(uid+1) is null        -- uid not in use
  14378.     if @uid is null
  14379.     begin
  14380.         raiserror(15065,-1,-1)
  14381.         return (1)
  14382.     end
  14383.  
  14384.     -- INSERT SYSUSERS ROW --
  14385.     insert into sysusers select
  14386.         @uid, @status | 2, @name_in_db, @sid, 0x00, getdate(), getdate(), 0, NULL
  14387.  
  14388.     -- INVALIDATE CACHED PERMISSIONS --
  14389.     grant all to null
  14390.  
  14391.     -- PRINT SUCCESS --
  14392.     raiserror(15341,-1,-1, @loginame)
  14393.  
  14394.     -- RETURN SUCCESS STATUS --
  14395.     return @@error -- sp_grantdbaccess
  14396. go
  14397.  
  14398. -- FOR BACKWARD COMPATIBILTY ONLY --
  14399. raiserror(15339,-1,-1,'sp_adduser')
  14400. go
  14401. create procedure sp_adduser
  14402.     @loginame       sysname,        -- user's login name in syslogins
  14403.     @name_in_db     sysname = NULL, -- user's name to add to current db
  14404.     @grpname        sysname = NULL  -- role to which user should be added.
  14405. as
  14406.     -- SETUP RUNTIME OPTIONS / DECLARE VARIABLES --
  14407.     set nocount on
  14408.     declare @ret        int
  14409.  
  14410.     -- LIMIT TO SQL/NT USERS IN SYSLOGINS (BCKWRD COMPAT ONLY!)
  14411.     if not exists (select * from master.dbo.syslogins where loginname = @loginame
  14412.             and (isntuser = 1 or isntname = 0))
  14413.         and @loginame <> 'guest'
  14414.     begin
  14415.         raiserror(15007,-1,-1,@loginame)
  14416.         return (1)
  14417.     end
  14418.  
  14419.     -- VALIDATE THE ROLENAME --
  14420.     if @grpname is not null and
  14421.        not exists (select * from sysusers where name = @grpname and issqlrole = 1)
  14422.     begin
  14423.         raiserror(15014,-1,-1,@grpname)
  14424.         return (1)
  14425.     end
  14426.  
  14427.     if @name_in_db is null
  14428.         select @name_in_db = @loginame
  14429.  
  14430.     -- In Hydra only the user dbo can do this --
  14431.     if (not is_member('dbo') = 1)
  14432.     begin
  14433.         -- AUDIT FAILED SECURITY CHECK --
  14434.         dbcc auditevent (109, 1, 0, @loginame, @name_in_db, @grpname , NULL)
  14435.         raiserror(15247,-1,-1)
  14436.         return (1)
  14437.     end
  14438.     else
  14439.     begin
  14440.         -- AUDIT SUCCESSFUL SECURITY CHECK --
  14441.         dbcc auditevent (109, 1, 1, @loginame, @name_in_db, @grpname , NULL)
  14442.     end
  14443.  
  14444.     -- ADD THE USER TO THE DATABASE --
  14445.     execute @ret = sp_grantdbaccess @loginame, @name_in_db OUT
  14446.     if (@ret <> 0)
  14447.         return (1)
  14448.  
  14449.     -- ADD USER TO ROLE IF GIVEN. NOP FOR 'public' --
  14450.     if (@grpname is not null) and (@grpname <> 'public')
  14451.     begin
  14452.         execute @ret = sp_addrolemember @grpname, @name_in_db
  14453.         if @ret <> 0
  14454.         begin
  14455.             -- ROLL BACK THE ABOVE sp_grantdbaccess --
  14456.             if @name_in_db = 'guest'
  14457.                 update sysusers set status = status & ~2, updatedate = getdate()
  14458.                             where name = 'guest'
  14459.             else
  14460.                 delete from sysusers where name = @name_in_db
  14461.             return (1)
  14462.         end
  14463.     end
  14464.  
  14465.     -- RETURN SUCCESS --
  14466.     return (0) -- sp_adduser
  14467. go
  14468.  
  14469. checkpoint
  14470. go
  14471.  
  14472. ----------------------------- sp_revokedbaccess -------------------------------
  14473.  
  14474. raiserror(15339,-1,-1,'sp_revokedbaccess')
  14475. go
  14476. create procedure sp_revokedbaccess
  14477.     @name_in_db     sysname
  14478. as
  14479.     -- SETUP RUNTIME OPTIONS / DECLARE VARIABLES --
  14480.     set nocount on
  14481.     declare @uid        smallint,
  14482.             @ret        int
  14483.  
  14484.     -- CHECK PERMISSIONS --
  14485.     if (not is_member('db_accessadmin') = 1) and
  14486.        (not is_member('db_owner') = 1)
  14487.     begin
  14488.         dbcc auditevent (109, 4, 0, NULL, @name_in_db, NULL, NULL)
  14489.         raiserror(15247,-1,-1)
  14490.         return (1)
  14491.     end
  14492.     else
  14493.     begin
  14494.         dbcc auditevent (109, 4, 1, NULL, @name_in_db, NULL, NULL)
  14495.     end
  14496.  
  14497.     -- DISALLOW USER TRANSACTION --
  14498.     set implicit_transactions off
  14499.     IF (@@trancount > 0)
  14500.     begin
  14501.         raiserror(15002,-1,-1,'sp_revokedbaccess')
  14502.         return (1)
  14503.     end
  14504.  
  14505.     -- CHECK IF SYSUSER EXISTS --
  14506.     select @uid = uid from sysusers where name = @name_in_db
  14507.             and (issqluser = 1 or isntname = 1)         -- is droppable entity
  14508.             and (name <> 'guest' or hasdbaccess = 1)    -- special case guest
  14509.     if @uid is null
  14510.     begin
  14511.         raiserror(15008,-1,-1,@name_in_db)
  14512.         return (1)
  14513.     end
  14514.  
  14515.     -- CANNOT DROP DBO/INFORMATION_SCHEMA/public --
  14516.     if @uid in (1,0,3,4) --dbo, public, INFORMATION_SCHEMA, system_function_schema
  14517.     begin
  14518.         raiserror(15181,-1,-1)
  14519.         return (1)
  14520.     end
  14521.  
  14522.     -- CANNOT DROP GUEST IN MASTER/TEMPDB --
  14523.     if lower(@name_in_db) = 'guest' and db_id() in (1, 2)
  14524.     begin
  14525.         raiserror(15182,-1,-1)
  14526.         return(1)
  14527.     end
  14528.  
  14529.     -- CHECK IF USER OWNS ANYTHING --
  14530.     execute @ret = sp_MScheck_uid_owns_anything @uid
  14531.     if @ret <> 0
  14532.         return (1)
  14533.  
  14534.     -- REMOVE SYSPERMISSIONS ROWS AND DEPENDENT ALIASES --
  14535.     delete from syspermissions where grantee = @uid
  14536.     if exists (select altuid from sysusers where altuid = @uid and isaliased = 1)
  14537.     begin
  14538.         delete from sysusers where altuid = @uid and isaliased = 1
  14539.            raiserror(15490,-1,-1)
  14540.     end
  14541.  
  14542.     -- DROP USER: SPECIAL HANDLING FOR GUEST (REMOVE HASDBACCESS) --
  14543.     if lower(@name_in_db) = 'guest'
  14544.         update sysusers set status = status & ~2, updatedate = getdate()
  14545.             where uid = user_id('guest')
  14546.     else
  14547.     begin
  14548.         delete from sysusers where uid = @uid
  14549.  
  14550.         delete from sysproperties where type =  2 and id = 0 and
  14551.         smallid = @uid
  14552.  
  14553.     end
  14554.     -- RETURN SUCCESS/FAILURE --
  14555.     if @@error <> 0
  14556.         return (1)
  14557.  
  14558.     -- INVALIDATE CACHED PERMISSIONS --
  14559.     grant all to null
  14560.  
  14561.     raiserror(15491,-1,-1)
  14562.     return (0) -- sp_revokedbaccess
  14563. go
  14564.  
  14565. -- FOR BACKWARD COMPATIBILTY ONLY --
  14566. raiserror(15339,-1,-1,'sp_dropuser')
  14567. go
  14568. create procedure sp_dropuser
  14569.     @name_in_db     sysname     -- user name to drop
  14570. as
  14571.     -- SETUP RUNTIME OPTIONS / DECLARE VARIABLES --
  14572.     set nocount on
  14573.     declare @ret    int
  14574.     declare @targetName sysname
  14575.     -- LIMIT TO SQL/NT USERS (BCKWRD COMPAT ONLY!)
  14576.     if not exists (select * from sysusers where name = @name_in_db
  14577.                     and (isntuser = 1 or isntname = 0))
  14578.     begin
  14579.         raiserror(15008,-1,-1,@name_in_db)
  14580.         return (1)
  14581.     end
  14582.     -- store target name
  14583.     select  @targetName = (select sl.name from master..syslogins sl,sysusers su where su.name = @name_in_db and su.sid = sl.sid)
  14584.  
  14585.     -- DROP THE USER FROM THE DATABASE --
  14586.     execute @ret = sp_revokedbaccess @name_in_db
  14587.     if @ret <> 0
  14588.     begin
  14589.         -- AUDIT FAILED SECURITY CHECK
  14590.     dbcc auditevent (109, 2, 0, @targetName, @name_in_db, NULL, NULL)
  14591.         return (1)
  14592.     end
  14593.  
  14594.     -- AUDIT SUCCESSFUL SECURITY CHECK --
  14595.     dbcc auditevent (109, 2, 1, @targetName, @name_in_db, NULL, NULL)
  14596.  
  14597.     -- FINALIZATION: PRINT/RETURN SUCCESS --
  14598.     return (0) -- sp_dropuser
  14599. go
  14600.  
  14601. -------------------------------- sp_addalias ----------------------------------
  14602.  
  14603. raiserror(15339,-1,-1,'sp_addalias')
  14604. go
  14605. create procedure sp_addalias
  14606.     @loginame       sysname,    -- name of the pretender
  14607.     @name_in_db     sysname     -- user to whom to alias the login
  14608. as
  14609.     -- SETUP RUNTIME OPTIONS / DECLARE VARIABLES --
  14610.     set nocount on
  14611.     declare @sid        varbinary(85),
  14612.             @targuid    smallint,
  14613.             @newuid     smallint,
  14614.             @status     smallint,
  14615.             @dbname     sysname
  14616.  
  14617.     -- CHECK PERMISSIONS --
  14618.     if (not is_member('db_accessadmin') = 1) and
  14619.        (not is_member('db_owner') = 1)
  14620.     begin
  14621.         raiserror(15247,-1,-1)
  14622.         return (1)
  14623.     end
  14624.  
  14625.     -- DISALLOW USER TRANSACTION --
  14626.     set implicit_transactions off
  14627.     IF (@@trancount > 0)
  14628.     begin
  14629.         raiserror(15002,-1,-1,'sp_addalias')
  14630.         return (1)
  14631.     end
  14632.  
  14633.     -- VALIDATE LOGIN NAME (OBTAIN SID) --
  14634.     select @status = CASE WHEN charindex('\', @loginame) > 0 THEN 12 ELSE 0 END
  14635.     if @status = 0
  14636.         select @sid = suser_sid(@loginame)          -- sql user
  14637.     -- retry sql user as nt with dflt domain
  14638.     if @sid is null
  14639.     begin
  14640.         select @sid = get_sid('\U'+@loginame, NULL) -- nt user
  14641.         if @sid is null
  14642.         begin
  14643.             if @status = 0
  14644.                 raiserror(15007,-1,-1,@loginame)
  14645.             else
  14646.                 raiserror(15401,-1,-1,@loginame)
  14647.             return (1)
  14648.         end
  14649.         select @status = 12
  14650.     end
  14651.     -- PREVENT USE OF CERTAIN LOGINS --
  14652.     else if @sid = 0x1
  14653.     begin
  14654.         raiserror(15405, -1, -1, @loginame)
  14655.         return (1)
  14656.     end
  14657.  
  14658.     -- VALIDATE NAME-IN-DB (OBTAIN TARGET UID) --
  14659.     select @targuid = uid from sysusers where name = @name_in_db
  14660.                         and (issqluser = 1 or isntuser = 1)
  14661.                         and uid NOT IN (3,4)    -- INFORMATION_SCHEMA, system_function_schema
  14662.     if @targuid is null
  14663.     begin
  14664.         raiserror(15008,-1,-1,@name_in_db)
  14665.         return (1)
  14666.     end
  14667.  
  14668.     -- ERROR IF LOGIN ALREADY IN DATABASE --
  14669.     if exists (select sid from sysusers where sid = @sid)
  14670.     begin
  14671.  
  14672.         -- ERROR IF ALREADY ALIASED --
  14673.         if exists (select sid from sysusers where sid = @sid and isaliased = 1)
  14674.         begin
  14675.             raiserror(15022,-1,-1)
  14676.             return (1)
  14677.         end
  14678.  
  14679.         -- ERROR: LOGIN ALREADY A USER --
  14680.         select @name_in_db = name, @dbname = db_name() from sysusers where sid = @sid
  14681.         raiserror(15278,-1,-1,@loginame,@name_in_db,@dbname)
  14682.         return (1)
  14683.     end
  14684.  
  14685.     -- ALTER NAME TO AVOID CONFLICTS IN NAME SPACE --
  14686.     select @loginame = '\' + @loginame
  14687.     if user_id(@loginame) is not null
  14688.     begin
  14689.         raiserror(15023,-1,-1,@loginame)
  14690.         return (1)
  14691.     end
  14692.  
  14693.     -- OBTAIN NEW UID (RESERVE 1-4) --
  14694.     if user_name(5) IS NULL
  14695.         select @newuid = 5
  14696.     else
  14697.         select @newuid = min(uid)+1 from sysusers
  14698.             where uid >= 5 and uid < (16384 - 1)    -- stay in users range
  14699.                 and user_name(uid+1) is null        -- uid not in use
  14700.     if @newuid is null
  14701.     begin
  14702.         raiserror(15065,-1,-1)
  14703.         return (1)
  14704.     end
  14705.  
  14706.     -- INSERT SYSUSERS ROW --
  14707.     insert into sysusers select
  14708.         @newuid, @status | 16, @loginame, @sid, 0x00,
  14709.                 getdate(), getdate(), @targuid, NULL
  14710.  
  14711.     -- FINALIZATION: PRINT/RETURN SUCCESS --
  14712.     if @@error <> 0
  14713.         return (1)
  14714.     raiserror(15340,-1,-1)
  14715.     return (0) -- sp_addalias
  14716. go
  14717.  
  14718. ------------------------------- sp_dropalias ----------------------------------
  14719.  
  14720. raiserror(15339,-1,-1,'sp_dropalias')
  14721. go
  14722. create procedure sp_dropalias
  14723.     @loginame   sysname     -- login who is currently aliased
  14724. as
  14725.     -- SETUP RUNTIME OPTIONS / DECLARE VARIABLES --
  14726.     set nocount on
  14727.     declare @sid        varbinary(85)
  14728.  
  14729.     -- CHECK PERMISSIONS --
  14730.     if (not is_member('db_accessadmin') = 1) and
  14731.        (not is_member('db_owner') = 1)
  14732.     begin
  14733.         raiserror(15247,-1,-1)
  14734.         return (1)
  14735.     end
  14736.  
  14737.     -- DISALLOW USER TRANSACTION --
  14738.     set implicit_transactions off
  14739.     IF (@@trancount > 0)
  14740.     begin
  14741.         raiserror(15002,-1,-1,'sp_dropalias')
  14742.         return (1)
  14743.     end
  14744.  
  14745.     -- VALIDATE LOGIN NAME (OBTAIN SID) --
  14746.     if charindex('\', @loginame) = 0
  14747.         select @sid = suser_sid(@loginame)          -- sql user
  14748.     if @sid is null
  14749.     begin
  14750.         select @sid = get_sid('\U'+@loginame, NULL) -- nt user
  14751.         if @sid is null
  14752.             begin
  14753.             -- Check directly for alias in sysusers
  14754.             SELECT @sid = sid FROM sysusers WHERE isaliased = 1 AND name = '\'+@loginame
  14755.             if @sid is null
  14756.             begin
  14757.                 if charindex('\', @loginame) = 0
  14758.                 raiserror(15007,-1,-1,@loginame)
  14759.                 else
  14760.                 raiserror(15401,-1,-1,@loginame)
  14761.                 return (1)
  14762.             end
  14763.         end
  14764.     end
  14765.  
  14766.     -- DELETE THE ALIAS (IF ANY) --
  14767.     delete from sysusers where sid = @sid and isaliased = 1
  14768.  
  14769.     -- ERROR IF NO ROW DELETED --
  14770.     if @@rowcount = 0
  14771.     begin
  14772.         raiserror(15134,-1,-1)
  14773.         return (1)
  14774.     end
  14775.  
  14776.     -- FINALIZATION: PRINT/RETURN SUCCESS --
  14777.     raiserror(15492,-1,-1)
  14778.     return (0) -- sp_dropalias
  14779. go
  14780.  
  14781. --------------------------------- sp_addrole ----------------------------------
  14782.  
  14783. raiserror(15339,-1,-1,'sp_addrole')
  14784. go
  14785. create procedure sp_addrole
  14786.     @rolename   sysname,        -- name of new role
  14787.     @ownername  sysname = 'dbo' -- name of owner of new role
  14788. as
  14789.     -- SETUP RUNTIME OPTIONS / DECLARE VARIABLES --
  14790.     set nocount on
  14791.     declare @ret        int,    -- return value of sp call
  14792.             @uid        smallint,
  14793.             @owner      smallint
  14794.  
  14795.     -- CHECK PERMISSIONS --
  14796.     if (not is_member('db_securityadmin') = 1) and
  14797.        (not is_member('db_owner') = 1)
  14798.     begin
  14799.         dbcc auditevent (111, 1, 0, NULL, NULL, @rolename, NULL)
  14800.         raiserror(15247,-1,-1)
  14801.         return (1)
  14802.     end
  14803.     else
  14804.     begin
  14805.         dbcc auditevent (111, 1, 1, NULL, NULL, @rolename, NULL)
  14806.     end
  14807.  
  14808.     -- DISALLOW USER TRANSACTION --
  14809.     set implicit_transactions off
  14810.     if (@@trancount > 0)
  14811.     begin
  14812.         raiserror(15002,-1,-1,'sp_addrole')
  14813.         return (1)
  14814.     end
  14815.  
  14816.         -- RESOLVE OWNER NAME --
  14817.     select @owner = uid from sysusers where name = @ownername
  14818.                     and isaliased = 0 AND uid NOT IN (0,3,4) --public/INFO_SCHEMA/etc can't own role
  14819.     if @owner is null
  14820.     begin
  14821.         raiserror(15008,-1,-1,@ownername)
  14822.         return (1)
  14823.     end
  14824.  
  14825.     -- VALIDATE ROLE NAME --
  14826.     execute @ret = sp_validname @rolename
  14827.     if @ret <> 0
  14828.         return (1)
  14829.     if (charindex('\', @rolename) > 0)
  14830.     begin
  14831.         raiserror(15006,-1,-1,@rolename)
  14832.         return (1)
  14833.     end
  14834.  
  14835.     if @rolename = 'sys'
  14836.         raiserror(15355,-1,-1)
  14837.  
  14838.     -- ERROR IF SYSUSERS NAME ALREADY EXISTS --
  14839.     if user_id(@rolename) is not null OR
  14840.         @rolename IN ('system_function_schema','INFORMATION_SCHEMA')
  14841.     begin
  14842.         if exists (select name from sysusers where issqlrole = 1 and name = @rolename)
  14843.             raiserror(15363,-1,-1,@rolename)
  14844.         else
  14845.             raiserror(15023,-1,-1,@rolename)
  14846.  
  14847.         return (1)
  14848.     end
  14849.  
  14850.     -- OBTAIN NEW ROLE UID (RESERVE 16384-16399) --
  14851.     if user_name(16400) IS NULL
  14852.         select @uid = 16400
  14853.     else
  14854.         select @uid = min(uid)+1 from sysusers
  14855.             where uid >= 16400 and uid < (32767 - 1)    -- stay in role range
  14856.                 and user_name(uid+1) is null            -- uid not in use
  14857.     if @uid is null
  14858.     begin
  14859.         raiserror(15065,-1,-1)
  14860.         return (1)
  14861.     end
  14862.  
  14863.     -- INSERT THE ROW INTO SYSUSERS --
  14864.     insert into sysusers values
  14865.         (@uid, 0, @rolename, NULL, 0x00, getdate(), getdate(), @owner, NULL)
  14866.  
  14867.     -- FINALIZATION: PRINT/RETURN SUCCESS --
  14868.     if @@error <> 0
  14869.         return (1)
  14870.     raiserror(15424,-1,-1)
  14871.     return (0) -- sp_addrole
  14872. go
  14873.  
  14874. -- FOR BACKWARD COMPATIBLIITY --
  14875. raiserror(15339,-1,-1,'sp_addgroup')
  14876. go
  14877. create procedure sp_addgroup
  14878.     @grpname   sysname         -- name of new role
  14879. as
  14880.     declare @ret int
  14881.     execute @ret = sp_addrole @grpname
  14882.     return @ret
  14883. go
  14884.  
  14885. -------------------------------- sp_droprole ----------------------------------
  14886.  
  14887. raiserror(15339,-1,-1,'sp_droprole')
  14888. go
  14889. create procedure sp_droprole
  14890.     @rolename       sysname     -- role to be dropped
  14891. as
  14892.     -- SETUP RUNTIME OPTIONS / DECLARE VARIABLES --
  14893.     set nocount on
  14894.     declare @uid        smallint,
  14895.             @owner      sysname,
  14896.             @ret        int
  14897.  
  14898.     -- DISALLOW USER TRANSACTION --
  14899.     set implicit_transactions off
  14900.     if (@@trancount > 0)
  14901.     begin
  14902.         raiserror(15002,-1,-1,'sp_droprole')
  14903.         return (1)
  14904.     end
  14905.  
  14906.     -- ROLE NAME (OBTAIN OWNER FOR PERMISSIONS) --
  14907.     select @uid = uid, @owner = user_name(altuid) from sysusers
  14908.             where name = @rolename and issqlrole = 1
  14909.  
  14910.     -- CHECK PERMISSIONS --
  14911.     if (not is_member('db_securityadmin') = 1) and
  14912.        (not is_member('db_owner') = 1) and
  14913.        (@owner is NULL or not is_member(@owner) = 1)
  14914.     begin
  14915.         dbcc auditevent (111, 2, 0, NULL, NULL, @rolename, NULL)
  14916.         raiserror(15247,-1,-1)
  14917.         return (1)
  14918.     end
  14919.     else
  14920.     begin
  14921.         dbcc auditevent (111, 2, 1, NULL, NULL, @rolename, NULL)
  14922.     end
  14923.  
  14924.     -- ERROR IF ROLE NOT FOUND --
  14925.     if @uid is null
  14926.     begin
  14927.         raiserror(15014,-1,-1,@rolename)
  14928.         return (1)
  14929.     end
  14930.  
  14931.     -- ERROR IF FIXED ROLE or PUBLIC ROLE--
  14932.     if @uid < 16400    or @uid = 0
  14933.     begin
  14934.         raiserror(15142,-1,-1, @rolename)
  14935.         return (1)
  14936.     end
  14937.  
  14938.     -- ERROR IF ANYONE IS MEMBER OF ROLE (DISPLAYS MEMBERS) --
  14939.     if exists (select * from sysmembers where groupuid = @uid)
  14940.     begin
  14941.         raiserror(15144,-1,-1)
  14942.         select name = user_name(memberuid) from sysmembers where groupuid = @uid
  14943.         return (1)
  14944.     end
  14945.  
  14946.     -- CHECK IF ROLE OWNS ANYTHING --
  14947.     execute @ret = sp_MScheck_uid_owns_anything @uid
  14948.     if @ret <> 0
  14949.         return (1)
  14950.  
  14951.     -- DROP SYSUSERS AND PROTECTION ENTRIES --
  14952.     delete from syspermissions where grantee = @uid
  14953.     delete from sysusers where uid = @uid
  14954.  
  14955.     -- FINALIZATION: PRINT/RETURN SUCCESS --
  14956.     if @@error <> 0
  14957.         return (1)
  14958.     raiserror(15493,-1,-1)
  14959.     return (0) -- sp_droprole
  14960. go
  14961.  
  14962.  
  14963. -- FOR BACKWARD COMPATIBLIITY --
  14964. raiserror(15339,-1,-1,'sp_dropgroup')
  14965. go
  14966. create procedure sp_dropgroup
  14967.     @rolename   sysname         -- name of role to drop
  14968. as
  14969.     declare @ret int
  14970.     execute @ret = sp_droprole @rolename
  14971.     return @ret
  14972. go
  14973.  
  14974.  
  14975. checkpoint
  14976. go
  14977.  
  14978. ------------------------------- sp_addapprole ---------------------------------
  14979.  
  14980. raiserror(15339,-1,-1,'sp_addapprole')
  14981. go
  14982. create procedure sp_addapprole
  14983.     @rolename   sysname,        -- name of new app role
  14984.     @password   sysname         -- password for app role
  14985. as
  14986.     -- SETUP RUNTIME OPTIONS / DECLARE VARIABLES --
  14987.     set nocount on
  14988.     declare @ret        int,    -- return value of sp call
  14989.             @uid        smallint
  14990.  
  14991.     -- CHECK FOR NULL PASSWORD
  14992.     if (@password is null)
  14993.     begin
  14994.         raiserror(15034,-1,-1)
  14995.         return (1)
  14996.     end
  14997.  
  14998.     -- CHECK PERMISSIONS --
  14999.     if (not is_member('db_securityadmin') = 1) and
  15000.        (not is_member('db_owner') = 1)
  15001.     begin
  15002.         raiserror(15247,-1,-1)
  15003.         return (1)
  15004.     end
  15005.  
  15006.     -- DISALLOW USER TRANSACTION --
  15007.     set implicit_transactions off
  15008.     if (@@trancount > 0)
  15009.     begin
  15010.         raiserror(15002,-1,-1,'sp_addapprole')
  15011.         return (1)
  15012.     end
  15013.  
  15014.     -- VALIDATE APPROLE NAME --
  15015.     execute @ret = sp_validname @rolename
  15016.     if @ret <> 0
  15017.         return (1)
  15018.     if (charindex('\', @rolename) > 0)
  15019.     begin
  15020.         raiserror(15006,-1,-1,@rolename)
  15021.         return (1)
  15022.     end
  15023.  
  15024.     if @rolename = 'sys'
  15025.         raiserror(15355,-1,-1)
  15026.  
  15027.     -- ERROR IF SYSUSERS NAME ALREADY EXISTS --
  15028.     if user_id(@rolename) is not null OR
  15029.         @rolename IN ('system_function_schema','INFORMATION_SCHEMA')
  15030.     begin
  15031.         raiserror(15363,-1,-1,@rolename)
  15032.         return (1)
  15033.     end
  15034.  
  15035.     -- OBTAIN NEW APPROLE UID (RESERVE 1-4) --
  15036.     if user_name(5) IS NULL
  15037.         select @uid = 5
  15038.     else
  15039.         select @uid = min(uid)+1 from sysusers
  15040.             where uid >= 5 and uid < (16384 - 1)    -- stay in users range
  15041.                 and user_name(uid+1) is null        -- uid not in use
  15042.     if @uid is null
  15043.     begin
  15044.         raiserror(15065,-1,-1)
  15045.         return (1)
  15046.     end
  15047.  
  15048.     -- INSERT THE ROW INTO SYSUSERS --
  15049.     insert into sysusers values
  15050.         (@uid, 32, @rolename, NULL, 0x00, getdate(),
  15051.                     getdate(), 1, convert(varbinary(256), pwdencrypt(@password)))
  15052.  
  15053.     -- FINALIZATION: PRINT/RETURN SUCCESS --
  15054.     if @@error <> 0
  15055.         return (1)
  15056.     raiserror(15425,-1,-1)
  15057.     return (0) -- sp_addapprole
  15058. go
  15059.  
  15060.  
  15061. ----------------------- sp_approlepassword -------------------------------------------
  15062.  
  15063. raiserror(15339,-1,-1,'sp_approlepassword')
  15064. go
  15065. CREATE PROCEDURE sp_approlepassword
  15066.     @rolename        sysname,            -- name of app role
  15067.     @newpwd            sysname                -- new password
  15068. AS
  15069.     declare @roluid        smallint
  15070.  
  15071.     -- CHECK FOR NULL PASSWORD
  15072.     if (@newpwd is null)
  15073.     begin
  15074.         raiserror(15034,-1,-1)
  15075.         return (1)
  15076.     end
  15077.  
  15078.     -- CHECK PERMISSIONS --
  15079.     if (not is_member('db_securityadmin') = 1) and
  15080.        (not is_member('db_owner') = 1)
  15081.     begin
  15082.         dbcc auditevent (112, 1, 0, NULL, NULL, @rolename, NULL)
  15083.         raiserror(15247,-1,-1)
  15084.         return (1)
  15085.     end
  15086.     else
  15087.     begin
  15088.         dbcc auditevent (112, 1, 1, NULL, NULL, @rolename, NULL)
  15089.     end
  15090.  
  15091.     -- DISALLOW USER TRANSACTION --
  15092.     set implicit_transactions off
  15093.     if (@@trancount > 0)
  15094.     begin
  15095.         raiserror(15002, -1, -1, 'sp_approlepassword')
  15096.         return (1)
  15097.     end
  15098.  
  15099.     -- ROLE UID (OBTAIN OWNER FOR PERMISSIONS) --
  15100.     -- @pwd will be encrypted.
  15101.     select @roluid = uid from sysusers
  15102.                 where name = @rolename and isapprole = 1
  15103.  
  15104.     -- ERROR IF APP ROLE NOT FOUND --
  15105.     if @roluid is null
  15106.     begin
  15107.         raiserror(15014, -1, -1, @rolename)
  15108.         return (1)
  15109.     end
  15110.  
  15111.     -- CHANGE PASSWORD --
  15112.     update sysusers set password = convert(varbinary(256), pwdencrypt(@newpwd)), updatedate = getdate()
  15113.             where uid = @roluid
  15114.     raiserror(15423,-1,-1,@rolename)
  15115.  
  15116.     return (0) -- sp_approlepassword
  15117. go
  15118.  
  15119.  
  15120. ------------------------------- sp_setapprole ---------------------------------
  15121.  
  15122. raiserror(15339,-1,-1,'sp_setapprole')
  15123. go
  15124. create procedure sp_setapprole
  15125.     @rolename   sysname,        -- name app role
  15126.     @password   sysname,        -- password for app role
  15127.     @encrypt    varchar(10)    = 'none'    -- Encryption style ('none' | 'odbc')
  15128. as
  15129.     -- SETUP RUNTIME OPTIONS / DECLARE VARIABLES --
  15130.     set nocount on
  15131.  
  15132.     -- DISALLOW USER TRANSACTION --
  15133.     set implicit_transactions off
  15134.     if (@@trancount > 0)
  15135.     begin
  15136.         raiserror(15002,-1,-1,'sp_setapprole')
  15137.         return (1)
  15138.     end
  15139.  
  15140.     -- CHECK PARAMETER
  15141.     if (@rolename IS NULL)
  15142.     begin
  15143.         raiserror(15431,-1,-1)
  15144.         return (1)
  15145.     end
  15146.  
  15147.     -- VALIDATE ENCRYPTION
  15148.     declare @encrStyle int
  15149.     select @encrStyle = case lower(@encrypt) when 'none' then 0 when 'odbc' then 1 else null end
  15150.     if @encrStyle is null
  15151.     begin
  15152.         raiserror(15600,-1,-1,'sp_setapprole')
  15153.         return (1)
  15154.     end
  15155.  
  15156.     -- SP MUST BE CALLED AT ADHOC LEVEL --
  15157.     if (@@nestlevel > 1)
  15158.     begin
  15159.         raiserror(15422,-1,-1)
  15160.         return (1)
  15161.     end
  15162.  
  15163.     -- ACTIVATE APPROLE (THIS IS ONLY VALID FROM THIS SP!) --
  15164.     setuser @rolename, @password, @encrStyle
  15165.  
  15166.     -- RETURN SUCCESS/FAILURE --
  15167.     if (@@error <> 0)
  15168.         return (1)
  15169.  
  15170.     raiserror(15494,-1,-1,@rolename)
  15171.  
  15172.     return (0) -- sp_setapprole
  15173. go
  15174.  
  15175. ------------------------------ sp_dropapprole ---------------------------------
  15176.  
  15177. raiserror(15339,-1,-1,'sp_dropapprole')
  15178. go
  15179. create procedure sp_dropapprole
  15180.     @rolename       sysname     -- role to be dropped
  15181. as
  15182.     -- SETUP RUNTIME OPTIONS / DECLARE VARIABLES --
  15183.     set nocount on
  15184.     declare @uid        smallint,
  15185.             @ret        int
  15186.  
  15187.     -- CHECK PERMISSIONS --
  15188.     if (not is_member('db_securityadmin') = 1) and
  15189.        (not is_member('db_owner') = 1)
  15190.     begin
  15191.         raiserror(15247,-1,-1)
  15192.         return (1)
  15193.     end
  15194.  
  15195.     -- DISALLOW USER TRANSACTION --
  15196.     set implicit_transactions off
  15197.     if (@@trancount > 0)
  15198.     begin
  15199.         raiserror(15002,-1,-1,'sp_dropapprole')
  15200.         return (1)
  15201.     end
  15202.  
  15203.     -- ERROR IF ROLE NOT FOUND --
  15204.     select @uid = uid from sysusers where name = @rolename and isapprole = 1
  15205.     if @uid is null
  15206.     begin
  15207.         raiserror(15014,-1,-1,@rolename)
  15208.         return (1)
  15209.     end
  15210.  
  15211.     -- CHECK IF ROLE OWNS ANYTHING --
  15212.     execute @ret = sp_MScheck_uid_owns_anything @uid
  15213.     if @ret <> 0
  15214.         return (1)
  15215.  
  15216.     -- DROP SYSUSERS AND PROTECTION ENTRIES --
  15217.     delete from syspermissions where grantee = @uid
  15218.     delete from sysusers where uid = @uid
  15219.  
  15220.     -- FINALIZATION: PRINT/RETURN SUCCESS --
  15221.     if @@error <> 0
  15222.         return (1)
  15223.     raiserror(15495,-1,-1)
  15224.     return (0) -- sp_dropapprole
  15225. go
  15226.  
  15227. ------------------------------ sp_addrolemember -------------------------------
  15228.  
  15229. raiserror(15339,-1,-1,'sp_addrolemember')
  15230. go
  15231. CREATE PROCEDURE sp_addrolemember
  15232.     @rolename       sysname,
  15233.     @membername     sysname
  15234. AS
  15235.     -- SETUP RUNTIME OPTIONS / DECLARE VARIABLES --
  15236.     set nocount on
  15237.     declare @roluid     smallint,
  15238.             @owner      smallint,
  15239.             @memuid     smallint,
  15240.             @ret        int
  15241.     declare @ruidbyte   smallint,
  15242.             @ruidbit    smallint
  15243.     declare @proc        nvarchar(50)
  15244.  
  15245.     -- DISALLOW USER TRANSACTION --
  15246.     set implicit_transactions off
  15247.     if (@@trancount > 0)
  15248.     begin
  15249.         raiserror(15002,-1,-1,'sp_addrolemember')
  15250.         return (1)
  15251.     end
  15252.  
  15253.     --cannot change membership of public
  15254.     if @rolename = 'public'
  15255.     begin
  15256.         raiserror(15081, -1,-1)
  15257.         return(1)
  15258.     end
  15259.  
  15260.     -- ROLE NAME (OBTAIN OWNER FOR PERMISSIONS) --
  15261.     select @roluid = uid, @owner = altuid from sysusers
  15262.                 where name = @rolename and issqlrole = 1
  15263.  
  15264.     -- ERROR IF ROLE NOT FOUND OR PUBLIC --
  15265.     if @roluid is null
  15266.     begin
  15267.         raiserror(15014,-1,-1,@rolename)
  15268.         return (1)
  15269.     end
  15270.  
  15271.     -- CHECK PERMISSIONS --
  15272.     -- Only member of db_owner can add members to db-fixed roles --
  15273.     if (not is_member('db_owner') = 1) and
  15274.        (not (@roluid < 16400 and is_member('db_owner') = 1)) and
  15275.        (not (@roluid >= 16400 and is_member('db_securityadmin') = 1)) and
  15276.        (not (@roluid >= 16400 and is_member(user_name(@owner)) = 1))
  15277.     begin
  15278.         dbcc auditevent (110, 1, 0, NULL, @membername, @rolename, NULL)
  15279.         raiserror(15247,-1,-1)
  15280.         return (1)
  15281.     end
  15282.     else
  15283.     begin
  15284.         dbcc auditevent (110, 1, 1, NULL, @membername, @rolename, NULL)
  15285.     end
  15286.  
  15287.     -- CHECK MEMBER NAME (ATTEMPT ADDING IMPLICIT ROW FOR NT NAME) --
  15288.     select @memuid = uid from sysusers where name = @membername and isaliased = 0
  15289.     if @memuid is null
  15290.     begin
  15291.         execute @ret = sp_MSadduser_implicit_ntlogin @membername
  15292.         select @memuid = uid from sysusers where name = @membername and isaliased = 0
  15293.     end
  15294.     if @memuid is null
  15295.     begin
  15296.         raiserror(15410, -1, -1, @membername)
  15297.         return (1)
  15298.     end
  15299.  
  15300.     -- CANNOT CHANGE MEMBERSHIP OF FIXED ROLES OR DBO --
  15301.     if @memuid in (1,0,3,4) --dbo, public, INFORMATION_SCHEMA, system_function_schema
  15302.         or (@memuid >= 16384 and @memuid < 16400)
  15303.     begin
  15304.         raiserror(15405, -1 ,-1, @membername)
  15305.         return (1)
  15306.     end
  15307.  
  15308.     -- CHECK FOR CIRCULAR MEMBERSHIPS --
  15309.     if is_userinrole(@rolename, @membername) = 1
  15310.     begin
  15311.         raiserror(15413, -1, -1)
  15312.         return (1)
  15313.     end
  15314.  
  15315.     -- SET ROLE BIT FOR THIS USER
  15316.     select @ruidbyte = ((@roluid - 16384) / 8) + 1
  15317.          , @ruidbit = power(2, @roluid & 7)
  15318.     update sysusers set roles = convert(varbinary(2048),
  15319.                 substring(convert(binary(2048), roles), 1, @ruidbyte-1)
  15320.                 + convert(binary(1), (@ruidbit) | substring(convert(binary(2048), roles), @ruidbyte, 1))
  15321.                 + substring(convert(binary(2048), roles), @ruidbyte+1, 2048-@ruidbyte) ),
  15322.             updatedate = getdate()
  15323.         where uid = @memuid
  15324.     -- END ROLE BIT MANIPULATION
  15325.  
  15326.     -- INVALIDATE CACHED PERMISSIONS (MEMBERSHIP CHANGES PERMISSIONS) --
  15327.     select @ret = @@error   -- save success state
  15328.     grant all to null
  15329.  
  15330.     -- FINALIZATION: PRINT/RETURN SUCCESS --
  15331.     if @@error <> 0 or @ret <> 0
  15332.         return (1)
  15333.  
  15334.     raiserror(15488,-1,-1,@membername,@rolename)
  15335.  
  15336.     return (0) -- sp_addrolemember
  15337. go
  15338.  
  15339. checkpoint
  15340. go
  15341.  
  15342. ----------------------------- sp_droprolemember -------------------------------
  15343.  
  15344. raiserror(15339,-1,-1,'sp_droprolemember')
  15345. go
  15346. CREATE PROCEDURE sp_droprolemember
  15347.     @rolename       sysname,
  15348.     @membername     sysname
  15349. AS
  15350.     -- SETUP RUNTIME OPTIONS / DECLARE VARIABLES --
  15351.     set nocount on
  15352.     declare @roluid     smallint,
  15353.             @owner      smallint,
  15354.             @memuid     smallint,
  15355.             @ret        int
  15356.     declare @ruidbyte   smallint,
  15357.             @ruidbit    smallint
  15358.     declare @proc        nvarchar(50)
  15359.  
  15360.     -- DISALLOW USER TRANSACTION --
  15361.     set implicit_transactions off
  15362.     if (@@trancount > 0)
  15363.     begin
  15364.         raiserror(15002,-1,-1,'sp_droprolemember')
  15365.         return (1)
  15366.     end
  15367.  
  15368.     --cannot change membership of public
  15369.     if @rolename = 'public'
  15370.     begin
  15371.         raiserror(15081, -1,-1)
  15372.         return(1)
  15373.     end
  15374.  
  15375.         -- ROLE NAME (OBTAIN OWNER FOR PERMISSIONS) --
  15376.     select @roluid = uid, @owner = altuid from sysusers
  15377.                 where name = @rolename and issqlrole = 1
  15378.  
  15379.     -- ERROR IF ROLE NOT FOUND OR PUBLIC --
  15380.     if @roluid is null
  15381.     begin
  15382.         raiserror(15409,-1,-1,@rolename)
  15383.         return (1)
  15384.     end
  15385.  
  15386.     -- CHECK PERMISSIONS --
  15387.     -- Only member of db_owner can drop members from db-fixed roles --
  15388.     if (not is_member('db_owner') = 1) and
  15389.        (not (@roluid < 16400 and is_member('db_owner') = 1)) and
  15390.        (not (@roluid >= 16400 and is_member('db_securityadmin') = 1)) and
  15391.        (not (@roluid >= 16400 and is_member(user_name(@owner)) = 1))
  15392.     begin
  15393.         dbcc auditevent (110, 2, 0, NULL, @membername, @rolename, NULL)
  15394.         raiserror(15247,-1,-1)
  15395.         return (1)
  15396.     end
  15397.     else
  15398.     begin
  15399.         dbcc auditevent (110, 2, 1, NULL, @membername, @rolename, NULL)
  15400.     end
  15401.  
  15402.     -- ERROR IF MEMBER NAME NOT NULL AND NOT FOUND --
  15403.     select @memuid = uid from sysusers where name = @membername and isaliased = 0
  15404.     if @memuid is null
  15405.     begin
  15406.         raiserror(15410, -1, -1, @membername)
  15407.         return (1)
  15408.     end
  15409.  
  15410.     -- CANNOT CHANGE MEMBERSHIP OF FIXED ROLES OR DBO --
  15411.     if @membername in ('dbo','public') or (@memuid >= 16384 and @memuid < 16400)
  15412.     begin
  15413.         raiserror(15405, -1 ,-1, @membername)
  15414.         return (1)
  15415.     end
  15416.  
  15417.     -- CLEAR ROLE BIT FOR THIS USER
  15418.     select @ruidbyte = ((@roluid - 16384) / 8) + 1
  15419.          , @ruidbit = power(2, @roluid & 7)
  15420.     update sysusers set roles = convert(varbinary(2048),
  15421.                 substring(convert(binary(2048), roles), 1, @ruidbyte-1)
  15422.                 + convert(binary(1), (~@ruidbit) & substring(convert(binary(2048), roles), @ruidbyte, 1))
  15423.                 + substring(convert(binary(2048), roles), @ruidbyte+1, 2048-@ruidbyte) ),
  15424.             updatedate = getdate()
  15425.         where uid = @memuid
  15426.     -- END ROLE BIT MANIPULATION
  15427.  
  15428.     -- INVALIDATE CACHED PERMISSIONS (MEMBERSHIP CHANGES PERMISSIONS) --
  15429.     select @ret = @@error   -- save success state
  15430.     grant all to null
  15431.  
  15432.     -- FINALIZATION: PRINT/RETURN SUCCESS --
  15433.     if @@error <> 0 or @ret <> 0
  15434.         return (1)
  15435.  
  15436.     raiserror(15489,-1,-1,@membername,@rolename)
  15437.  
  15438.     return (0) -- sp_droprolemember
  15439. go
  15440.  
  15441. ------------------------------- sp_changegroup --------------------------------
  15442.  
  15443. raiserror(15339,-1,-1,'sp_changegroup')
  15444. go
  15445. create procedure sp_changegroup
  15446.     @grpname    sysname,    -- name of new role
  15447.     @username   sysname     -- user to switch
  15448. as
  15449.     -- SETUP RUNTIME OPTIONS / DECLARE VARIABLES --
  15450.     set nocount on
  15451.     declare @uid        smallint,
  15452.             @ruid        smallint,
  15453.             @cnt        int,
  15454.             @ret        int,
  15455.             @oldgrp     sysname
  15456.  
  15457.      select @ruid = uid from sysusers
  15458.                 where name = @grpname and issqlrole = 1
  15459.  
  15460.     -- ERROR IF GROUP NOT FOUND --
  15461.     if @ruid is null
  15462.     begin
  15463.         raiserror(15014,-1,-1,@grpname)
  15464.         return (1)
  15465.     end
  15466.  
  15467.     -- LIMIT TO USERS WITH ACCESS (BACKWARD COMPAT ONLY!) --
  15468.     select @uid = uid from sysusers where name = @username
  15469.                 and (issqluser = 1 or isntuser = 1) and hasdbaccess = 1
  15470.     if @uid is null
  15471.     begin
  15472.         raiserror(15008,-1,-1,@username)
  15473.         return (1)
  15474.     end
  15475.  
  15476.     -- ONLY VALID IF USER IS MEMBER OF NO MORE THAN ONE GROUP --
  15477.     select @cnt = count(*) from sysmembers where memberuid = @uid
  15478.     if @cnt > 1
  15479.     begin
  15480.         raiserror(15415, -1, -1)
  15481.         return (1)
  15482.     end
  15483.  
  15484.     -- AUDIT SUCCESSFUL SECURITY CHECK --
  15485.     dbcc auditevent (110, 3, 1, NULL, @username, @grpname, NULL)
  15486.  
  15487.     -- REMOVE MEMBERSHIP IF NEEDED --
  15488.     if (@cnt = 1)
  15489.     begin
  15490.         select @oldgrp = user_name(groupuid) from sysmembers where memberuid = @uid
  15491.         execute @ret = sp_droprolemember @oldgrp, @username
  15492.         if @ret <> 0
  15493.             return (1)
  15494.     end
  15495.  
  15496.     -- ADD MEMBERSHIP --
  15497.     if (@grpname <> 'public')
  15498.     begin
  15499.         execute @ret = sp_addrolemember @grpname, @username
  15500.         if @ret <> 0
  15501.             return (1)
  15502.     end
  15503.  
  15504.     -- FINALIZATION: RETURN SUCCESS --
  15505.     raiserror(15496,-1,-1)
  15506.  
  15507.     return (0) -- sp_changegroup
  15508. go
  15509.  
  15510. ---------------------------- sp_change_users_login ----------------------------
  15511.  
  15512. raiserror(15339,-1,-1,'sp_change_users_login')
  15513. go
  15514. CREATE PROCEDURE sp_change_users_login
  15515.     @Action               varchar(10)       -- REPORT / UPDATE_ONE / AUTO_FIX
  15516.    ,@UserNamePattern      sysname  = Null
  15517.    ,@LoginName            sysname  = Null
  15518.    ,@Password              sysname  = Null
  15519. AS
  15520.     -- SETUP RUNTIME OPTIONS / DECLARE VARIABLES --
  15521.     set nocount on
  15522.     declare @exec_stmt nvarchar(430)
  15523.  
  15524.     declare @ret            int,
  15525.             @FixMode        char(5),
  15526.             @cfixesupdate   int,        -- count of fixes by update
  15527.             @cfixesaddlogin int,        -- count of fixes by sp_addlogin
  15528.             @dbname         sysname,
  15529.             @loginsid       varbinary(85),
  15530.             @110name        sysname
  15531.  
  15532.     -- SET INITIAL VALUES --
  15533.     select  @dbname         = db_name(),
  15534.             @cfixesupdate   = 0,
  15535.             @cfixesaddlogin = 0
  15536.  
  15537.     -- ERROR IF IN USER TRANSACTION --
  15538.     if @@trancount > 0
  15539.     begin
  15540.         raiserror(15289,-1,-1)
  15541.         return (1)
  15542.     end
  15543.  
  15544.     -- INVALIDATE USE OF SPECIAL LOGIN/USER NAMES --
  15545.     if suser_sid(@LoginName) = 0x1    -- 'sa'
  15546.     begin
  15547.         raiserror(15287,-1,-1,@LoginName)
  15548.         return (1)
  15549.     end
  15550.     if user_id(@UserNamePattern) in (1,0,3,4) --dbo, public, INFORMATION_SCHEMA, system_function_schema
  15551.     begin
  15552.         raiserror(15287,-1,-1,@UserNamePattern)
  15553.         return (1)
  15554.     end
  15555.  
  15556.     -- HANDLE REPORT --
  15557.     if upper(@Action) = 'REPORT'
  15558.     begin
  15559.  
  15560.         -- VALIDATE PARAMS --
  15561.         if @UserNamePattern IS NOT Null or @LoginName IS NOT Null
  15562.         begin
  15563.             raiserror(15290,-1,-1,@Action,@UserNamePattern,@LoginName)
  15564.             return (1)
  15565.         end
  15566.  
  15567.         -- GENERATE REPORT --
  15568.         select UserName = name, UserSID = sid from sysusers
  15569.             where issqluser = 1 and (sid is not null and sid <> 0x0)
  15570.                     and suser_sname(sid) is null
  15571.             order by name
  15572.         return (0)
  15573.     end
  15574.  
  15575.     -- HANDLE UPDATE_ONE --
  15576.     if upper(@Action) = 'UPDATE_ONE'
  15577.     begin
  15578.  
  15579.         -- CHECK PERMISSIONS --
  15580.         if not is_member('db_owner') = 1
  15581.         begin
  15582.             raiserror(15247,-1,-1)
  15583.             return (1)
  15584.         end
  15585.  
  15586.         -- ERROR IF PARAMS NULL --
  15587.         if @UserNamePattern IS Null or @LoginName IS Null
  15588.         begin
  15589.             raiserror(15290,-1,-1,@Action,@UserNamePattern,@LoginName)
  15590.             return (1)
  15591.         end
  15592.  
  15593.         -- VALIDATE PARAMS --
  15594.         -- Can ONLY remap SQL Users to SQL Logins!  Should be no need
  15595.         --  for re-mapping NT logins, and if you try, you'll mess up
  15596.         --  the user status bits! 
  15597.         if not exists (select name from sysusers where
  15598.                 name = @UserNamePattern             -- match user name
  15599.             and issqluser = 1)                      -- must be sql user
  15600.         begin
  15601.             raiserror(15291,-1,-1,'User',@UserNamePattern)
  15602.             return (1)
  15603.         end
  15604.         select @loginsid = sid from master.dbo.syslogins where
  15605.                 loginname = @LoginName              -- match login name
  15606.             and isntname = 0                        -- cannot use nt logins
  15607.         if @loginsid is null
  15608.         begin
  15609.             raiserror(15291,-1,-1,'Login',@LoginName)
  15610.             return (1)
  15611.         end
  15612.  
  15613.         -- ERROR IF SID ALREADY IN USE IN DATABASE --
  15614.         if exists (select sid from sysusers where sid = @loginsid
  15615.                     and name <> @UserNamePattern)
  15616.         begin
  15617.             raiserror(15063,-1,-1)
  15618.             return (1)
  15619.         end
  15620.  
  15621.         -- CHANGE THE USERS LOGIN (SID) --
  15622.         update sysusers set sid = @loginsid, updatedate = getdate()
  15623.                 where name = @UserNamePattern and issqluser = 1
  15624.                 and sid <> @loginsid
  15625.  
  15626.         -- FINALIZATION: REPORT (ONLY IF NOT SUCCESSFUL) AND EXIT --
  15627.         if @@error <> 0 or @@rowcount <> 1
  15628.             raiserror(15295,-1,-1, 0)
  15629.         return (0)
  15630.     end
  15631.  
  15632.     -- ERROR IF NOT AUTO_FIX --
  15633.     if upper(@Action) <> 'AUTO_FIX'
  15634.     begin
  15635.         raiserror(15286,-1,-1,@Action)
  15636.         return (1)
  15637.     end
  15638.  
  15639.     -- HANDLE AUTO_FIX --
  15640.     -- CHECK PERMISSIONS --
  15641.     if not is_srvrolemember('sysadmin') = 1
  15642.     begin
  15643.         raiserror(15247,-1,-1)
  15644.         return (1)
  15645.     end
  15646.  
  15647.     -- VALIDATE PARAMS --
  15648.     if @UserNamePattern IS Null or @LoginName IS NOT Null
  15649.     begin
  15650.         raiserror(15290,-1,-1,@Action,@UserNamePattern,@LoginName)
  15651.         return (1)
  15652.     end
  15653.  
  15654.     -- LOOP THRU ORPHANED USERS --
  15655.     select @exec_stmt = 'DECLARE ms_crs_110_Users cursor global for
  15656.             select name from sysusers
  15657.             where name = N' + quotename( @UserNamePattern , '''')+ '
  15658.                 and issqluser = 1 and suser_sname(sid) is null'
  15659.     EXECUTE (@exec_stmt)
  15660.     OPEN ms_crs_110_Users
  15661.  
  15662.     WHILE (110=110)
  15663.     begin
  15664.         FETCH next from ms_crs_110_Users into @110name
  15665.         if (@@fetch_status <> 0)
  15666.         begin
  15667.             DEALLOCATE ms_crs_110_Users
  15668.             BREAK
  15669.         end
  15670.  
  15671.         -- IS NAME ALREADY IN USE? --
  15672.         -- if suser_sid(@110name) is null
  15673.         if not exists(select * from master.dbo.syslogins where loginname = @110name)
  15674.         begin
  15675.  
  15676.            -- VALIDATE PARAMS --
  15677.             if @Password IS Null
  15678.             begin
  15679.                 raiserror(15290,-1,-1,@Action,@UserNamePattern,@LoginName)
  15680.                 return (1)
  15681.             end
  15682.  
  15683.             -- ADD LOGIN --
  15684.             execute @ret = sp_addlogin @110name, @Password, @dbname
  15685.             if @ret <> 0 or suser_sid(@110name) is null
  15686.             begin
  15687.                 raiserror(15497,16,1,@110name)
  15688.                 deallocate ms_crs_110_Users
  15689.                 return (1)
  15690.             end
  15691.             select @FixMode = '1AddL'
  15692.             raiserror(15293,-1,-1,@110name)
  15693.         end
  15694.         ELSE
  15695.         begin
  15696.             Select @FixMode = '2UpdU'
  15697.             Raiserror(15292,-1,-1,@110name)
  15698.         end
  15699.  
  15700.         -- REPORT ERROR & CONTINUE IF DUPLICATE SID IN DB --
  15701.         select @loginsid = suser_sid(@110name)
  15702.         if user_sid(@loginsid) is not null
  15703.         begin
  15704.             raiserror(15331,-1,-1,@110name)
  15705.             CONTINUE
  15706.         end
  15707.  
  15708.         -- UPDATE SYSUSERS ROW --
  15709.         update sysusers set sid = @loginsid, updatedate = getdate(), status = (status & ~1) | 2 where name = @110name
  15710.         if @@error <> 0
  15711.         begin
  15712.             raiserror(15498,17,127)
  15713.             deallocate ms_crs_110_Users
  15714.             return (1)
  15715.         end
  15716.  
  15717.  
  15718.         if @FixMode = '1AddL'
  15719.             Select @cfixesaddlogin = @cfixesaddlogin + 1
  15720.         else
  15721.             Select @cfixesupdate = @cfixesupdate + 1
  15722.     end -- loop 110
  15723.  
  15724.     -- REPORT AND RETURN SUCCESS --
  15725.     raiserror(15295,-1,-1,@cfixesupdate)
  15726.     raiserror(15294,-1,-1,@cfixesaddlogin)
  15727.     return (0) -- sp_change_users_login
  15728. go
  15729.  
  15730. ------------------------------ sp_changedbowner -------------------------------
  15731.  
  15732. raiserror(15339,-1,-1,'sp_changedbowner')
  15733. go
  15734. create procedure sp_changedbowner
  15735.     @loginame       sysname,        -- login to become dbo
  15736.     @map            varchar(5) = NULL    -- True to map aliases, else drop
  15737. as
  15738.     -- SETUP RUNTIME OPTIONS / DECLARE VARIABLES --
  15739.     set nocount on
  15740.     declare @ret        int,
  15741.             @newsid     varbinary(85),
  15742.             @status     smallint
  15743.  
  15744.     -- CHECK PERMISSIONS (Note: All sysadmins are dbo) --
  15745.     -- See Bug Shiloh 362190 ---
  15746.     if not (is_srvrolemember('sysadmin') = 1)
  15747.     begin
  15748.         raiserror(15247,-1,-1)
  15749.         return(1)
  15750.     end
  15751.  
  15752.     -- CANT CHANGE OWNER OF MASTER/MODEL/TEMPDB --
  15753.     if db_name() in ('master', 'model', 'tempdb')
  15754.     begin
  15755.         raiserror(15109,-1,-1)
  15756.         return(1)
  15757.     end
  15758.  
  15759.     -- CHECK LOGIN NAME IS VALID (NT/SQL USER ONLY!) --
  15760.     select @newsid = sid, @status = 2 from master.dbo.syslogins
  15761.                     where loginname = @loginame and isntname = 0
  15762.     if @newsid is null
  15763.         select @status = 14, @newsid = get_sid('\U'+@loginame, NULL)
  15764.     if @newsid is null
  15765.     begin
  15766.         raiserror(15007,-1,-1,@loginame)
  15767.         return (1)
  15768.     end
  15769.  
  15770.     -- CHECK IF LOGIN ALREADY ALIASED IN DB --
  15771.     if exists (select sid from sysusers where isaliased = 1 and sid = @newsid)
  15772.     begin
  15773.         raiserror(15111,-1,-1)
  15774.         return (1)
  15775.     end
  15776.  
  15777.     -- CHECK IF LOGIN ALREADY KNOWN TO DATABASE --
  15778.     if exists (select sid from sysusers where sid = @newsid and uid <> 1)
  15779.     begin
  15780.         raiserror(15110,-1,-1)
  15781.         return (1)
  15782.     end
  15783.  
  15784.  
  15785.     -- MAKE THE FOLLOWING REMOVE/REMAP/DELETES ATOMIC --
  15786.     begin transaction
  15787.  
  15788.     -- REMAP DBO TO NEW SID --
  15789.     update sysusers set sid = @newsid, status = @status, updatedate = getdate()
  15790.             where name = 'dbo'
  15791.  
  15792.     -- REMOVE OTHER DBO-ALIASES IF REMAPPING NOT REQUESTED --
  15793.     if lower(@map) <> 'true'
  15794.     begin
  15795.         delete from sysusers where isaliased = 1 and altuid = user_id('dbo')
  15796.         raiserror(15500,-1,-1)
  15797.     end
  15798.     else
  15799.         raiserror(15499,-1,-1)     -- nothing to do to <remap>
  15800.  
  15801.     -- REFLECT NEW OWNER IN SYSDATABASES --
  15802.     update master.dbo.sysdatabases set sid = @newsid where dbid = db_id()
  15803.     commit transaction
  15804.  
  15805.     -- CHECKPOINT DATABASE TO FORCE CHANGES TO IN-MEMORY STRUCTURE --
  15806.     checkpoint
  15807.     raiserror(15501,-1,-1)
  15808.     grant all to null
  15809.     return (0) -- sp_changedbowner
  15810. go
  15811.  
  15812. ------------------------- sp_check_removable_sysusers -------------------------
  15813.  
  15814. raiserror(15339,-1,-1,'sp_check_removable_sysusers')
  15815. go
  15816. -----------------------------------------------------
  15817. -- NOTE: FOR INTERNAL USE ONLY (sp_certify_removable)
  15818. --      DO NOT DOCUMENT OR USE!
  15819. -----------------------------------------------------
  15820. create procedure sp_check_removable_sysusers
  15821.     @autofix    varchar(4)      -- true or other
  15822. as
  15823.     -- CHECK FOR DATABASE OWNED BY SQL USER --
  15824.     if exists (select name from sysusers where name = 'dbo' and issqluser = 1 and sid <> suser_sid('sa'))
  15825.     begin
  15826.         if @autofix <> 'auto'
  15827.         begin
  15828.             raiserror(15258,-1,-1)
  15829.             return(1)
  15830.         end
  15831.  
  15832.         -- MAKE SA THE DBO --
  15833.         raiserror(15502,-1,-1)
  15834.         update sysusers set sid = suser_sid('sa'), status = 2, updatedate = getdate()
  15835.                 where name = 'dbo'
  15836.     end
  15837.  
  15838.     -- CHECK FOR PERMISSIONS GRANTED TO or BY SQL USERS --
  15839.     if exists (select grantee from syspermissions where grantee in
  15840.                 (select uid from sysusers u where issqluser = 1 and u.uid > 4))
  15841.     OR exists (select grantor from syspermissions where grantor in
  15842.                 (select uid from sysusers u where issqluser = 1 and u.uid > 4))
  15843.     begin
  15844.         if @autofix = 'auto'
  15845.             PRINT 'CANNOT AUTO-AUTOFIX GRANT-WITH-GRANT CHAINS'
  15846.         raiserror(15053,-1,-1)
  15847.         return(1)
  15848.     end
  15849.  
  15850.     -- CHECK FOR OBJECTS OWNED BY SQL USERS --
  15851.     if exists (select uid from sysobjects where uid in
  15852.                 (select uid from sysusers u where issqluser = 1 and u.uid > 4))
  15853.     begin
  15854.         if @autofix <> 'auto'
  15855.         begin
  15856.             raiserror(15053,-1,-1)
  15857.             return(1)
  15858.         end
  15859.  
  15860.         -- ASSIGN DBO AS OWNER OF OTHER OBJECTS (MAY FAIL WITH DUPL!) --
  15861.         raiserror(15503,-1,-1)
  15862.         update sysobjects set uid = 1 where uid in
  15863.                 (select uid from sysusers u where issqluser = 1 and u.uid > 4)
  15864.         if @@error <> 0
  15865.             return (1)
  15866.     end
  15867.  
  15868.     -- CHECK FOR TYPES OWNED BY SQL USERS --
  15869.     if exists (select uid from systypes where uid in
  15870.                 (select uid from sysusers u where issqluser = 1 and u.uid > 4))
  15871.     begin
  15872.         if @autofix <> 'auto'
  15873.         begin
  15874.             raiserror(15053,-1,-1)
  15875.             return(1)
  15876.         end
  15877.  
  15878.         -- ASSIGN DBO AS OWNER OF TYPES --
  15879.         raiserror(15503,-1,-1)
  15880.         update systypes set uid = 1 where uid in
  15881.                 (select uid from sysusers u where issqluser = 1 and u.uid > 4)
  15882.     end
  15883.  
  15884.     -- CHECK FOR ROLES OWNED BY SQL USERS --
  15885.     if exists (select altuid from sysusers where (issqlrole = 1 or isapprole = 1) and
  15886.         altuid in (select uid from sysusers u where u.issqluser = 1 and u.uid > 4))
  15887.     begin
  15888.         if @autofix <> 'auto'
  15889.         begin
  15890.             raiserror(15053,-1,-1)
  15891.             return(1)
  15892.         end
  15893.  
  15894.         -- ASSIGN DBO AS OWNER OF TYPES --
  15895.         raiserror(15503,-1,-1)
  15896.         update sysusers set altuid = 1, updatedate = getdate()
  15897.             where (issqlrole = 1 or isapprole = 1) and
  15898.             altuid in (select uid from sysusers u where u.issqluser = 1 and u.uid > 4)
  15899.     end
  15900.  
  15901.     -- CHECK FOR SQL LOGINS AS USERS --
  15902.     if exists (select uid from sysusers where issqluser = 1 and uid > 4)
  15903.     begin
  15904.         if @autofix <> 'auto'
  15905.         begin
  15906.             raiserror(15254,-1,-1)
  15907.             return(1)
  15908.         end
  15909.  
  15910.         -- DELETE SQL USERS AND DEPENDENT ALIASES --
  15911.         raiserror(15504,-1,-1)
  15912.         delete from sysusers where issqluser = 1 and uid > 4
  15913.         delete from sysusers where isaliased = 1 and user_name(altuid) is null
  15914.     end
  15915.  
  15916.     -- CHECK FOR SQL LOGINS ALIASED --
  15917.     if exists (select uid from sysusers where isaliased = 1 and isntname = 0)
  15918.     begin
  15919.         if @autofix <> 'auto'
  15920.         begin
  15921.             raiserror(15254,-1,-1)
  15922.             return(1)
  15923.         end
  15924.  
  15925.         -- DELETE ALIASED SQL USERS --
  15926.         raiserror(15504,-1,-1)
  15927.         delete from sysusers where isaliased = 1 and isntname = 0
  15928.     end
  15929.  
  15930.     -- Success
  15931.     return 0
  15932. go
  15933.  
  15934. checkpoint
  15935. go
  15936.  
  15937. ---------------------------- sp_changeobjectowner -----------------------------
  15938.  
  15939. raiserror(15339,-1,-1,'sp_changeobjectowner')
  15940. go
  15941. create procedure sp_changeobjectowner
  15942.     @objname    nvarchar(517),        -- may be "[owner].[object]"
  15943.     @newowner    sysname                -- must be entry from sysusers
  15944. as
  15945.     Set nocount      on
  15946.     Set ansi_padding on
  15947.     declare    @objid        int,
  15948.             @newuid        smallint
  15949.  
  15950.     -- CHECK PERMISSIONS: Because changing owner changes both schema and
  15951.     --    permissions, the caller must be one of:
  15952.     -- (1) db_owner
  15953.     -- (2) db_ddladmin AND db_securityadmin
  15954.     if (is_member('db_owner') = 0) and
  15955.         (is_member('db_securityadmin') = 0 OR is_member('db_ddladmin') = 0)
  15956.     begin
  15957.         raiserror(15247,-1,-1)
  15958.         return (1)
  15959.     end
  15960.  
  15961.     -- RESOLVE OBJECT NAME (CANNOT BE A CHILD OBJECT: TRIGGER/CONSTRAINT) --
  15962.     select @objid = object_id(@objname, 'local')
  15963.     if (@objid is null) OR
  15964.         (select parent_obj from sysobjects where id = @objid) <> 0 OR
  15965.         ObjectProperty(@objid, 'IsMSShipped') = 1 OR
  15966.         ObjectProperty(@objid, 'IsSystemTable') = 1 OR
  15967.         ObjectProperty(@objid, 'ownerid') in (0,3,4) OR --public, INFORMATION_SCHEMA, system_function_schema
  15968.         -- Check for Dependencies: No RENAME or CHANGEOWNER of OBJECT when exists:
  15969.         EXISTS (SELECT * FROM sysdepends d WHERE
  15970.             d.depid = @objid        -- A dependency on this object
  15971.             AND d.deptype > 0        -- that is enforced
  15972.             AND @objid <> d.id        -- that isn't a self-reference (self-references don't use object name)
  15973.             AND @objid <>            -- And isn't a reference from a child object (also don't use object name)
  15974.                 (SELECT o.parent_obj FROM sysobjects o WHERE o.id = d.id)
  15975.             )
  15976.     begin
  15977.         -- OBJECT NOT FOUND
  15978.         raiserror(15001,-1,-1,@objname)
  15979.         return 1
  15980.     end
  15981.  
  15982.     -- RESOLVE NEW OWNER NAME (ATTEMPT ADDING IMPLICIT ROW FOR NT NAME) --
  15983.     --  Disallow aliases, and public cannot own objects --
  15984.     select @newuid = uid from sysusers where name = @newowner
  15985.                             and isaliased = 0
  15986.                             and uid not in (0,3,4) --public, INFORMATION_SCHEMA, system_function_schema
  15987.     if @newuid is null
  15988.     begin
  15989.         execute sp_MSadduser_implicit_ntlogin @newowner
  15990.         select @newuid = uid from sysusers where name = @newowner
  15991.                             and isaliased = 0 and name <> 'public'
  15992.     end
  15993.     if @newuid is null
  15994.     begin
  15995.         raiserror(15410, -1, -1, @newowner)
  15996.         return (1)
  15997.     end
  15998.  
  15999.     -- CHECK IF CHANGING OWNER OF OBJECT OR ITS CHILDREN WOULD PRODUCE A DUPLICATE
  16000.     if exists (select * from sysobjects where uid = @newuid and name in
  16001.         (select name from sysobjects where id = @objid OR parent_obj = @objid))
  16002.     begin
  16003.         raiserror(15505,-1,-1,@objname,@newowner)
  16004.         return (1)
  16005.     end
  16006.  
  16007.  
  16008.     -- DO THE OWNER TRANSFER (WITH A WARNING) --
  16009.     raiserror(15477,-1,-1)
  16010.     begin transaction
  16011.     -- Locks Object and increments schema_ver.
  16012.     DBCC LockObjectSchema(@objname)
  16013.     -- drop permissions (they'll be incorrect with new owner) --
  16014.     delete syspermissions where id = @objid
  16015.     update sysobjects set uid = @newuid where id = @objid
  16016.     update sysobjects set uid = @newuid where parent_obj = @objid
  16017.     commit transaction
  16018.  
  16019.     return 0    -- sp_changeobjectowner
  16020. go
  16021.  
  16022. -- GRANT PUBLIC ACCESS (SP'S DO INTERNAL PERMISSIONS CHECKS) --
  16023. grant execute on sp_grantdbaccess to public
  16024. grant execute on sp_revokedbaccess to public
  16025. grant execute on sp_adduser to public
  16026. grant execute on sp_dropuser to public
  16027. grant execute on sp_addalias to public
  16028. grant execute on sp_dropalias to public
  16029. grant execute on sp_addrole to public
  16030. grant execute on sp_droprole to public
  16031. grant execute on sp_dropgroup to public
  16032. grant execute on sp_addgroup to public
  16033. grant execute on sp_dropgroup to public
  16034. grant execute on sp_addapprole to public
  16035. grant execute on sp_approlepassword to public
  16036. grant execute on sp_setapprole to public
  16037. grant execute on sp_dropapprole to public
  16038. grant execute on sp_addrolemember to public
  16039. grant execute on sp_droprolemember to public
  16040. grant execute on sp_changegroup to public
  16041. grant execute on sp_change_users_login to public
  16042. grant execute on sp_changedbowner to public
  16043. grant execute on sp_changeobjectowner to public
  16044. go
  16045. /**********************  END DATABASE-ACCESS-SECURITY ************************/
  16046.  
  16047. /******************************************************************************
  16048. ************************  SECURITY-HELP-PROCEDURES  ***************************
  16049. ******************************************************************************/
  16050. checkpoint
  16051. go
  16052. if object_id('sp_helpsrvrole','P') IS NOT NULL
  16053.     drop procedure sp_helpsrvrole
  16054. if object_id('sp_srvrolepermission','P') IS NOT NULL
  16055.     drop procedure sp_srvrolepermission
  16056. if object_id('sp_helpsrvrolemember','P') IS NOT NULL
  16057.     drop procedure sp_helpsrvrolemember
  16058. if object_id('sp_helpdbfixedrole','P') IS NOT NULL
  16059.     drop procedure sp_helpdbfixedrole
  16060. if object_id('sp_dbfixedrolepermission','P') IS NOT NULL
  16061.     drop procedure sp_dbfixedrolepermission
  16062. if object_id('sp_helprolemember','P') IS NOT NULL
  16063.     drop procedure sp_helprolemember
  16064. if object_id('sp_helprole','P') IS NOT NULL
  16065.     drop procedure sp_helprole
  16066. if object_id('sp_helpntgroup','P') IS NOT NULL
  16067.     drop procedure sp_helpntgroup
  16068. if object_id('xp_logininfo','P') IS NOT NULL
  16069.     drop procedure xp_logininfo
  16070. go
  16071.  
  16072.  
  16073. ----------------------- sp_helpsrvrole ----------------------------------------
  16074.  
  16075. raiserror(15339,-1,-1,'sp_helpsrvrole')
  16076. go
  16077. CREATE PROCEDURE sp_helpsrvrole
  16078.     @srvrolename        sysname = NULL
  16079. AS
  16080.     if @srvrolename is not null
  16081.     begin
  16082.         -- VALIDATE GIVEN NAME
  16083.         if not exists (select * from master.dbo.spt_values
  16084.                 where name = @srvrolename and low = 0 and type = 'SRV')
  16085.         begin
  16086.             raiserror(15412, -1, -1, @srvrolename)
  16087.             return (1)
  16088.         end
  16089.  
  16090.         -- RESULT SET FOR SINGLE SERVER-ROLE
  16091.         select 'ServerRole' = v1.name, 'Description' = v2.name
  16092.             from master.dbo.spt_values v1, master.dbo.spt_values v2
  16093.             where v1.name = @srvrolename and
  16094.                   v1.low = 0 and
  16095.                   v1.type = 'SRV' and
  16096.                   v2.low = -1 and
  16097.                   v2.type = 'SRV' and
  16098.                   v1.number = v2.number
  16099.     end
  16100.     else
  16101.     begin
  16102.         -- RESULT SET FOR ALL SERVER-ROLES
  16103.         select 'ServerRole' = v1.name, 'Description' = v2.name
  16104.             from master.dbo.spt_values v1, master.dbo.spt_values v2
  16105.             where v1.low = 0 and
  16106.                   v1.type = 'SRV' and
  16107.                   v2.low = -1 and
  16108.                   v2.type = 'SRV' and
  16109.                   v1.number = v2.number
  16110.     end
  16111.  
  16112.     return (0) -- sp_helpsrvrole
  16113. go
  16114.  
  16115. ----------------------- sp_srvrolepermission ----------------------------------
  16116.  
  16117. raiserror(15339,-1,-1,'sp_srvrolepermission')
  16118. go
  16119. CREATE PROCEDURE sp_srvrolepermission
  16120.     @srvrolename       sysname = NULL
  16121. AS
  16122.     if @srvrolename is not null
  16123.     begin
  16124.         -- VALIDATE GIVEN NAME
  16125.         if not exists (select * from master.dbo.spt_values
  16126.                 where name = @srvrolename and low = 0 and type = 'SRV')
  16127.         begin
  16128.             raiserror(15412, -1, -1, @srvrolename)
  16129.             return (1)
  16130.         end
  16131.  
  16132.         -- RESULT SET FOR SINGLE SERVER-ROLE
  16133.         select distinct 'ServerRole' = v1.name, 'Permission' = v2.name
  16134.             from master.dbo.spt_values v1, master.dbo.spt_values v2
  16135.             where v1.name = @srvrolename and
  16136.                   v1.low = 0 and
  16137.                   v1.type = 'SRV' and
  16138.                   ((v2.type = 'SRV' and ((v1.number = 16 and v1.number <= v2.number) or (v1.number <> 16 and v1.number = v2.number))) or
  16139.                   (v2.type = 'DBR' and v1.number = 16 and not (v2.name like N'No %'))) and
  16140.                   v2.low > 0
  16141.             order by v1.name, v2.name
  16142.     end
  16143.     else
  16144.     begin
  16145.         -- RESULT SET FOR ALL SERVER-ROLES
  16146.         select distinct 'ServerRole' = v1.name, 'Permission' = v2.name
  16147.             from master.dbo.spt_values v1, master.dbo.spt_values v2
  16148.             where v1.low = 0 and
  16149.                   v1.type = 'SRV' and
  16150.                   ((v2.type = 'SRV' and ((v1.number = 16 and v1.number <= v2.number) or (v1.number <> 16 and v1.number = v2.number))) or
  16151.                   (v2.type = 'DBR' and v1.number = 16 and not (v2.name like N'No %'))) and
  16152.                   v2.low > 0
  16153.             order by v1.name, v2.name
  16154.     end
  16155.  
  16156.     return (0) -- sp_srvrolepermission
  16157. go
  16158.  
  16159.  
  16160. ----------------------- sp_helpsrvrolemember ----------------------------------
  16161.  
  16162. raiserror(15339,-1,-1,'sp_helpsrvrolemember')
  16163. go
  16164. CREATE PROCEDURE sp_helpsrvrolemember
  16165.     @srvrolename       sysname = NULL
  16166. AS
  16167.     if @srvrolename is not null
  16168.     begin
  16169.         -- VALIDATE GIVEN NAME
  16170.         if not exists (select * from master.dbo.spt_values
  16171.                 where name = @srvrolename and low = 0 and type = 'SRV')
  16172.         begin
  16173.             raiserror(15412, -1, -1, @srvrolename)
  16174.             return (1)
  16175.         end
  16176.  
  16177.         -- RESULT SET FOR SINGLE SERVER-ROLE
  16178.         select 'ServerRole' = spv.name, 'MemberName' = lgn.name, 'MemberSID' = lgn.sid
  16179.             from master.dbo.spt_values spv, master.dbo.sysxlogins lgn
  16180.             where spv.name = @srvrolename and
  16181.                   spv.low = 0 and
  16182.                   spv.type = 'SRV' and
  16183.                   lgn.srvid IS NULL and
  16184.                   spv.number & lgn.xstatus = spv.number
  16185.     end
  16186.     else
  16187.     begin
  16188.         -- RESULT SET FOR ALL SERVER-ROLES
  16189.         select 'ServerRole' = spv.name, 'MemberName' = lgn.name, 'MemberSID' = lgn.sid
  16190.             from master.dbo.spt_values spv, master.dbo.sysxlogins lgn
  16191.             where spv.low = 0 and
  16192.                   spv.type = 'SRV' and
  16193.                   lgn.srvid IS NULL and
  16194.                   spv.number & lgn.xstatus = spv.number
  16195.     end
  16196.  
  16197.     return (0) -- sp_helpsrvrolemember
  16198. go
  16199.  
  16200. ----------------------- sp_helpdbfixedrole ----------------------------------------
  16201.  
  16202. raiserror(15339,-1,-1,'sp_helpdbfixedrole')
  16203. go
  16204. CREATE PROCEDURE sp_helpdbfixedrole
  16205.     @rolename        sysname = NULL
  16206. AS
  16207.     if @rolename is not null
  16208.     begin
  16209.         -- VALIDATE GIVEN NAME
  16210.         if not exists (select * from sysusers where name = @rolename
  16211.                         and uid >= 16384 and uid <= 16393)
  16212.         begin
  16213.             raiserror(15412, -1, -1, @rolename)
  16214.             return (1)
  16215.         end
  16216.  
  16217.         -- RESULT SET FOR SINGLE FIXED-ROLE
  16218.         select 'DbFixedRole' = usr.name, 'Description' = spv.name
  16219.             from sysusers usr, master.dbo.spt_values spv
  16220.             where usr.name = @rolename and
  16221.                   usr.uid >= 16384 and
  16222.                   usr.uid <= 16393 and
  16223.                   usr.uid = spv.number and
  16224.                   spv.type = 'DBR' and
  16225.                   spv.low = -1
  16226.     end
  16227.     else
  16228.     begin
  16229.         -- RESULT SET FOR ALL FIXED-ROLES
  16230.         select 'DbFixedRole' = usr.name, 'Description' = spv.name
  16231.             from sysusers usr, master.dbo.spt_values spv
  16232.             where usr.uid >= 16384 and
  16233.                   usr.uid <= 16393 and
  16234.                   usr.uid = spv.number and
  16235.                   spv.type = 'DBR' and
  16236.                   spv.low = -1
  16237.     end
  16238.  
  16239.     return (0) -- sp_helpdbfixedrole
  16240. go
  16241.  
  16242.  
  16243. ----------------------- sp_dbfixedrolepermission ------------------------------
  16244.  
  16245. raiserror(15339,-1,-1,'sp_dbfixedrolepermission')
  16246. go
  16247. CREATE PROCEDURE sp_dbfixedrolepermission
  16248.     @rolename       sysname = NULL
  16249. AS
  16250.     if @rolename is not null
  16251.     begin
  16252.         -- VALIDATE GIVEN NAME
  16253.         if not exists (select * from sysusers where name = @rolename
  16254.                         and uid >= 16384 and uid <= 16393)
  16255.         begin
  16256.             raiserror(15412, -1, -1, @rolename)
  16257.             return (1)
  16258.         end
  16259.  
  16260.         -- RESULT SET FOR SINGLE FIXED-ROLE
  16261.         select DISTINCT 'DbFixedRole' = usr.name, 'Permission' = spv.name
  16262.             from sysusers usr, master.dbo.spt_values spv
  16263.             where usr.name = @rolename and
  16264.                   usr.uid >= 16384 and
  16265.                   usr.uid <= 16393 and
  16266.                   spv.type = 'DBR' and
  16267.                   ((usr.uid = 16384 and spv.number >= 16384 and spv.number < 16392) or (usr.uid <> 16384 and usr.uid = spv.number)) and
  16268.                   spv.low > 0
  16269.             order by usr.name, spv.name
  16270.     end
  16271.     else
  16272.     begin
  16273.         -- RESULT SET FOR ALL FIXED-ROLES
  16274.         select DISTINCT 'DbFixedRole' = usr.name, 'Permission' = spv.name
  16275.             from sysusers usr, master.dbo.spt_values spv
  16276.             where usr.uid >= 16384 and
  16277.                   usr.uid <= 16393 and
  16278.                   spv.type = 'DBR' and
  16279.                   ((usr.uid = 16384 and spv.number >= 16384 and spv.number < 16392) or (usr.uid <> 16384 and usr.uid = spv.number)) and
  16280.                   spv.low > 0
  16281.             order by usr.name, spv.name
  16282.     end
  16283.  
  16284.     return (0) -- sp_dbfixedrolepermission
  16285. go
  16286.  
  16287.  
  16288. ----------------------- sp_helprolemember -------------------------------------
  16289.  
  16290. raiserror(15339,-1,-1,'sp_helprolemember')
  16291. go
  16292. CREATE PROCEDURE sp_helprolemember
  16293.     @rolename       sysname = NULL
  16294. AS
  16295.     if @rolename is not null
  16296.     begin
  16297.         -- VALIDATE GIVEN NAME
  16298.         if not exists (select * from sysusers where name = @rolename and issqlrole = 1)
  16299.         begin
  16300.             raiserror(15409, -1, -1, @rolename)
  16301.             return (1)
  16302.         end
  16303.  
  16304.         -- RESULT SET FOR SINGLE ROLE
  16305.         select DbRole = g.name, MemberName = u.name, MemberSID = u.sid
  16306.             from sysusers u, sysusers g, sysmembers m
  16307.             where g.name = @rolename
  16308.                 and g.uid = m.groupuid
  16309.                 and g.issqlrole = 1
  16310.                 and u.uid = m.memberuid
  16311.             order by 1, 2
  16312.     end
  16313.     else
  16314.     begin
  16315.         -- RESULT SET FOR ALL ROLES
  16316.         select DbRole = g.name, MemberName = u.name, MemberSID = u.sid
  16317.             from sysusers u, sysusers g, sysmembers m
  16318.             where   g.uid = m.groupuid
  16319.                 and g.issqlrole = 1
  16320.                 and u.uid = m.memberuid
  16321.             order by 1, 2
  16322.     end
  16323.  
  16324.     return (0) -- sp_helprolemember
  16325. go
  16326.  
  16327.  
  16328. ----------------------- sp_helprole -------------------------------------------
  16329.  
  16330. raiserror(15339,-1,-1,'sp_helprole')
  16331. go
  16332. CREATE PROCEDURE sp_helprole
  16333.     @rolename       sysname = NULL
  16334. AS
  16335.     if @rolename is not null
  16336.     begin
  16337.         -- VALIDATE GIVEN NAME
  16338.         if not exists (select * from sysusers where name = @rolename and (issqlrole = 1 or isapprole = 1))
  16339.         begin
  16340.             raiserror(15409, -1, -1, @rolename)
  16341.             return (1)
  16342.         end
  16343.  
  16344.         -- RESULT SET FOR SINGLE ROLE
  16345.         select 'RoleName' = name, 'RoleId' = uid, 'IsAppRole' = isapprole
  16346.             from sysusers where (name = @rolename) and (issqlrole = 1 or isapprole = 1)
  16347.     end
  16348.     else
  16349.     begin
  16350.         -- RESULT SET FOR ALL ROLES
  16351.         select 'RoleName' = name, 'RoleId' = uid, 'IsAppRole' = isapprole
  16352.             from sysusers where issqlrole = 1 or isapprole = 1
  16353.     end
  16354.  
  16355.     return (0) -- sp_helprole
  16356. go
  16357.  
  16358.  
  16359. ----------------------- sp_helpntgroup ----------------------------------------
  16360.  
  16361. raiserror(15339,-1,-1,'sp_helpntgroup')
  16362. go
  16363. CREATE PROCEDURE sp_helpntgroup
  16364.     @ntname       sysname = NULL
  16365. AS
  16366.     if @ntname is not null
  16367.     begin
  16368.         -- VALIDATE GIVEN NAME
  16369.         if not exists (select * from sysusers where name = @ntname and isntgroup = 1)
  16370.         begin
  16371.             raiserror(15420, -1, -1, @ntname)
  16372.             return (1)
  16373.         end
  16374.  
  16375.         -- RESULT SET FOR SINGLE GROUP
  16376.         select 'NTGroupName' = name, 'NtGroupId' = uid, 'SID' = sid, 'HasDbAccess' = hasdbaccess
  16377.             from sysusers where name = @ntname and isntgroup = 1
  16378.     end
  16379.     else
  16380.     begin
  16381.         -- RESULT SET FOR ALL GROUPS
  16382.         select 'NTGroupName' = name, 'NtGroupId' = uid, 'SID' = sid, 'HasDbAccess' = hasdbaccess
  16383.             from sysusers where isntgroup = 1
  16384.     end
  16385.  
  16386.     return (0) -- sp_helpntgroup
  16387. go
  16388.  
  16389. ------------------------------- xp_logininfo ----------------------------------
  16390.  
  16391. create proc xp_logininfo
  16392.     @acctname        sysname = null,                -- IN: NT login name
  16393.     @option            varchar(10) = null,            -- IN: 'all' | 'members' | null
  16394.     @privilege        varchar(10) = 'Not wanted' OUTPUT    -- OUT: 'admin' | 'user' | null
  16395. as
  16396.     -- VALIDATE PARAMETERS --
  16397.     if (@acctname is null AND (@option is not null OR (@privilege is null OR @privilege <> 'Not wanted')))
  16398.         OR ((@option is null OR @option <> 'all') AND (@privilege is null OR @privilege <> 'Not wanted'))
  16399.         OR (@option is not null and @option not in ('all', 'members'))
  16400.     begin
  16401.         raiserror(15600,-1,-1,'xp_logininfo')
  16402.         return 1
  16403.     end
  16404.  
  16405.     -- HANDLE CASE WHERE NO @acctname GIVEN --
  16406.     if (@acctname is null)
  16407.     begin
  16408.         select    'account name' = loginname,
  16409.                 'type' = convert(varchar(8), case when isntuser = 1 then 'user' else 'group' end),
  16410.                 'privilege' = convert(varchar(8), case when sysadmin = 1 then 'admin' else 'user' end),
  16411.                 'mapped login name' = loginname,
  16412.                 'permission path' = convert(sysname, null)
  16413.         from master..syslogins where isntname = 1 and hasaccess = 1
  16414.         order by 3, 1
  16415.         return @@error
  16416.     end
  16417.  
  16418.     -- HANDLE 'members' QUERY --
  16419.     if (@option = 'members')
  16420.     begin
  16421.         declare @priv varchar(8)
  16422.         select @priv = case when sysadmin = 1 then 'admin' else 'user' end
  16423.             from master..syslogins where isntname = 1 and loginname = @acctname and hasaccess = 1
  16424.         if @priv is not null
  16425.             select    'account name' = domain+N'\'+name,
  16426.                     'type' = convert(varchar(8), case when sidtype = 1 then 'user' else 'group' end),
  16427.                     'privilege' = @priv,
  16428.                     'mapped login name' = domain+N'\'+name,
  16429.                     'permission path' = @acctname
  16430.             from OpenRowset(NetGroupGetMembers, @acctname) order by 3, 1
  16431.         else
  16432.             select    'account name' = convert(sysname, null),
  16433.                     'type' = convert(varchar(8), null),
  16434.                     'privilege' = @priv,
  16435.                     'mapped login name' = convert(sysname, null),
  16436.                     'permission path' = convert(sysname, null)
  16437.             where 0=1    -- empty result set
  16438.         return @@error
  16439.     end
  16440.  
  16441.     -- CREATE TEMP TABLE AND POPULATE WITH THE REQUIRED DATA --
  16442.     create table #nt (name sysname collate database_default, sid varbinary(85), sidtype int)
  16443.     insert #nt select loginname, sid, isntgroup + 1 from master..syslogins
  16444.             where isntname = 1 and loginname = @acctname
  16445.     insert #nt select distinct domain+N'\'+name, sid, sidtype
  16446.             from OpenRowset(NetUserGetGroups, @acctname)
  16447.     if @@error <> 0
  16448.         return @@error
  16449.     -- IF ANY DENY, THEN NO ACCESS --
  16450.     if exists (select * from master..syslogins where sid in (select #nt.sid from #nt) and denylogin = 1)
  16451.         delete #nt
  16452.  
  16453.     -- HANDLE CASE WHERE OUTPUT REQUESTED --
  16454.     if (@privilege is null OR @privilege <> 'Not wanted')
  16455.     begin
  16456.         select @privilege = case max(sysadmin)
  16457.             when 1 then 'admin'
  16458.             when 0 then 'user'
  16459.             else NULL end
  16460.         from master..syslogins where isntname = 1 and hasaccess = 1
  16461.             AND sid in (select sid from #nt)
  16462.         return @@error
  16463.     end
  16464.  
  16465.     -- GET NT TYPE FOR NEXT OPTIONS --
  16466.     declare @type varchar(8)
  16467.     select @type = case when get_sid('\U'+@acctname, NULL) is null then 'group' else 'user' end
  16468.  
  16469.     -- HANDLE 'all' QUERY --
  16470.     if (@option = 'all')
  16471.     begin
  16472.         select    'account name' = @acctname,
  16473.                 'type' = @type,
  16474.                 'privilege' = convert(varchar(8), case when sysadmin = 1 then 'admin' else 'user' end),
  16475.                 'mapped login name' = @acctname,
  16476.                 'permission path' = case when l.loginname = @acctname then NULL else l.loginname end
  16477.         from master..syslogins l join #nt n on l.isntname = 1 and l.sid = n.sid
  16478.         where l.loginname = n.name and hasaccess = 1
  16479.         order by 3, 5
  16480.         return @@error
  16481.     end
  16482.  
  16483.     -- HANDLE DEFAULT QUERY --
  16484.     select    TOP 1
  16485.             'account name' = @acctname,
  16486.             'type' = @type,
  16487.             'privilege' = convert(varchar(8), case when sysadmin = 1 then 'admin' else 'user' end),
  16488.             'mapped login name' = @acctname,
  16489.             'permission path' = case when l.loginname = @acctname then NULL else l.loginname end
  16490.     from master..syslogins l join #nt n on l.isntname = 1 and l.sid = n.sid
  16491.     where l.loginname = n.name and hasaccess = 1
  16492.     order by 3, 5
  16493.     return @@error
  16494. go
  16495.  
  16496. -- GRANT PUBLIC ACCESS --
  16497. grant execute on sp_helpsrvrole            to public
  16498. grant execute on sp_srvrolepermission      to public
  16499. grant execute on sp_helpsrvrolemember      to public
  16500. grant execute on sp_helpdbfixedrole           to public
  16501. grant execute on sp_dbfixedrolepermission  to public
  16502. grant execute on sp_helprolemember         to public
  16503. grant execute on sp_helprole               to public
  16504. grant execute on sp_helpntgroup            to public
  16505. -- NOTE: No grant for xp_logininfo! (it has no internal perm checks)
  16506. go
  16507. /************************  END-SECURITY-HELP-PROCEDURES  *********************/
  16508.  
  16509. /******************************************************************************
  16510. **************************  SYSSERVER-STORED-PROCS  ***************************
  16511. ******************************************************************************/
  16512. checkpoint
  16513. go
  16514. if object_id('sp_addlinkedserver','P') IS NOT NULL
  16515.     drop procedure sp_addlinkedserver
  16516. if object_id('sp_dropserver','P') IS NOT NULL
  16517.     drop procedure sp_dropserver
  16518. if object_id('sp_serveroption','P') IS NOT NULL
  16519.     drop procedure sp_serveroption
  16520. if object_id('sp_addserver','P') IS NOT NULL
  16521.     drop procedure sp_addserver
  16522. if object_id('sp_setnetname','P') IS NOT NULL
  16523.     drop procedure sp_setnetname
  16524. if object_id('sp_helpserver','P') IS NOT NULL
  16525.     drop procedure sp_helpserver
  16526. if object_id('sp_helplinkedsrvlogin','P') IS NOT NULL
  16527.     drop procedure sp_helplinkedsrvlogin
  16528. go
  16529.  
  16530.  
  16531. ----------------------------- sp_addlinkedserver ------------------------------
  16532.  
  16533. raiserror(15339,-1,-1,'sp_addlinkedserver')
  16534. go
  16535. create procedure sp_addlinkedserver
  16536.     @server         sysname,                -- server name
  16537.     @srvproduct     nvarchar(128) = NULL,   -- product name (dflt to ss)
  16538.     @provider       nvarchar(128) = NULL,   -- oledb provider name
  16539.     @datasrc        nvarchar(4000) = NULL,  -- oledb datasource property
  16540.     @location       nvarchar(4000) = NULL,  -- oledb location property
  16541.     @provstr        nvarchar(4000) = NULL,  -- oledb provider-string property
  16542.     @catalog        sysname = NULL          -- oledb catalog property
  16543. as
  16544.     -- VARIABLES
  16545.     declare @retcode    int,
  16546.             @srvid      smallint,
  16547.             @srvstat    smallint
  16548.  
  16549.     -- DISALLOW USER TRANSACTION
  16550.     set implicit_transactions off
  16551.     if @@trancount > 0
  16552.     begin
  16553.         raiserror(15002,-1,-1,'sp_addlinkedserver')
  16554.         return (1)
  16555.     end
  16556.  
  16557.     -- CHECK PERMISSIONS
  16558.     if not (is_srvrolemember('setupadmin') = 1)
  16559.     begin
  16560.         raiserror(15247,-1,-1)
  16561.         return (1)
  16562.     end
  16563.  
  16564.     -- VALIDATE SERVER NAME
  16565.     execute @retcode = sp_validname @server
  16566.     if @retcode <> 0
  16567.         return (1)
  16568.  
  16569.     -- SET DEFAULT STATUS BITS
  16570.     select @srvstat = 32 | 128  | 1024 -- local login mapping = 32, data access = 128 , use remote collation = 1024
  16571.  
  16572.     -- VALIDATE OLEDB PARAMETERS
  16573.     if @provider is null
  16574.     begin
  16575.         -- NO PROVIDER MEANS CANNOT SPECIFY ANY PROPERTIES!
  16576.         if @datasrc is not null or @location is not null or @provstr is not null or @catalog is not null
  16577.         begin
  16578.             raiserror(15426,-1,-1)
  16579.             return (1)
  16580.         end
  16581.  
  16582.         -- THIS MUST BE A WELL-KNOWN SERVER TYPE (DEFAULT IS SS)
  16583.         if @srvproduct is null OR lower(@srvproduct) = N'sql server'
  16584.         begin
  16585.             select @srvproduct = N'SQL Server'  -- force case to be this
  16586.             select @provider = N'SQLOLEDB'      -- SQL Server provider (LUXOR)
  16587.             select @datasrc = @server           -- datasrc is (network) server name
  16588.                         -- For SQL Server, we want rpc in/out by default
  16589.             select @srvstat = @srvstat | 1 | 64
  16590.                         -- rpc = 1, rpc out = 64
  16591.         end
  16592.         else            -- ADD OTHER WELL-KNOWN SOURCES HERE
  16593.         begin
  16594.             raiserror(15427,-1,-1,@srvproduct)
  16595.             return (1)
  16596.         end
  16597.     end
  16598.     else if @srvproduct in (N'SQL Server')  -- WELL-KNOWN SOURCES
  16599.     begin
  16600.         -- ILLEGAL TO SPECIFY PROVIDER/PROPERTIES FOR WELL-KNOWN SOURCES
  16601.         raiserror(15428,-1,-1,@srvproduct)
  16602.         return (1)
  16603.     end
  16604.     else if @srvproduct is null or lower(@srvproduct) like N'%sql server%'
  16605.     begin
  16606.         raiserror(15429,-1,-1,@srvproduct)
  16607.         return (1)
  16608.     end
  16609.  
  16610.     -- CHECK IF SERVER ALREADY EXISTS
  16611.     if exists (select * from master.dbo.sysservers where srvname = @server)
  16612.     begin
  16613.         raiserror(15028,-1,-1,@server)
  16614.         return (1)
  16615.     end
  16616.  
  16617.     -- GET SERVER ID FOR NEW ROW
  16618.     if not exists (select * from master.dbo.sysservers where srvid = 1)
  16619.         select @srvid = 1
  16620.     else
  16621.         select @srvid = min(s.srvid)+1 from master.dbo.sysservers s
  16622.             where s.srvid < 32767 and not exists
  16623.                 (select * from master.dbo.sysservers s2 where s2.srvid = s.srvid+1)
  16624.     if @srvid is null
  16625.     begin
  16626.         raiserror(15430,-1,-1)
  16627.         return (1)
  16628.     end
  16629.  
  16630.     -- ADD ROW TO SYSSERVERS
  16631.     BEGIN TRAN
  16632.     insert master.dbo.sysservers select @srvid, @srvstat, @server, @srvproduct,
  16633.                 @provider, @datasrc, @location, @provstr, getdate(), NULL, NULL, @catalog, NULL, 0, 0
  16634.  
  16635.     -- INSERT may have failed with row-too-big error.
  16636.     IF @@ERROR <> 0
  16637.     BEGIN
  16638.         ROLLBACK TRAN
  16639.         RETURN (1)
  16640.     END
  16641.  
  16642.     -- ADD DEFAULT MAPPING FOR OUTGOING EVENTS
  16643.     insert into master.dbo.sysxlogins select
  16644.         @srvid, NULL, 192, getdate(), getdate(), NULL, NULL, 0, NULL
  16645.     COMMIT TRAN
  16646.  
  16647.     -- SUCCESS
  16648.     return (0) -- sp_addlinkedserver
  16649. go
  16650.  
  16651.  
  16652. ------------------------------- sp_dropserver ---------------------------------
  16653.  
  16654. raiserror(15339,-1,-1,'sp_dropserver')
  16655. go
  16656. create procedure sp_dropserver
  16657.     @server     sysname,            -- server name
  16658.     @droplogins char(10) = NULL     -- drop all related logins?
  16659. as
  16660.     declare @ret int
  16661.  
  16662.     -- DISALLOW USER TRANSACTION
  16663.     set implicit_transactions off
  16664.     if @@trancount > 0
  16665.     begin
  16666.         raiserror(15002,-1,-1,'sp_dropserver')
  16667.         return (1)
  16668.     end
  16669.  
  16670.     -- CHECK PERMISSIONS
  16671.     if not (is_srvrolemember('setupadmin') = 1)
  16672.     begin
  16673.         raiserror(15247,-1,-1)
  16674.         return (1)
  16675.     end
  16676.  
  16677.  
  16678.     -- CHECK SERVER NAME / GET SERVER ID
  16679.     declare @srvid smallint
  16680.     select @srvid = srvid from master.dbo.sysservers where srvname = @server
  16681.     if @srvid is null
  16682.     begin
  16683.         raiserror(15015,-1,-1,@server)
  16684.         return (1)
  16685.     end
  16686.  
  16687.     -- CHECK @droplogins PARAMETER (FOR RELATED SYSREMOTELOGINS ROWS)
  16688.     if @droplogins is null
  16689.     begin
  16690.         -- DONT consider default mapping for outgoing events
  16691.         if exists (select * from master.dbo.sysxlogins
  16692.                     where srvid = @srvid and
  16693.                           not(ishqoutmap = 1 and
  16694.                               xstatus&192 = 192 and
  16695.                               sid is null and
  16696.                               name is null and
  16697.                               password is null))
  16698.         begin
  16699.             raiserror(15190,-1,-1,@server)
  16700.             return (1)
  16701.         end
  16702.     end
  16703.     else if @droplogins <> 'droplogins'
  16704.     begin
  16705.         raiserror(15191,-1,-1)
  16706.         return (1)
  16707.     end
  16708.  
  16709.     -- CHECK TO SEE IF THE SERVER IS USED BY REPLICATION.
  16710.     if object_id('master.dbo.sp_MSrepl_check_server') is not null
  16711.     begin
  16712.         execute @ret = master.dbo.sp_MSrepl_check_server @server
  16713.         if @ret <> 0 or @@error <> 0
  16714.             return 1
  16715.     end
  16716.  
  16717.     -- DROP THE SERVER (ALONG WITH ANY REMOTE LOGINS)
  16718.     begin transaction
  16719.     delete master.dbo.sysxlogins where srvid = @srvid
  16720.     delete master.dbo.sysservers where srvid = @srvid
  16721.     commit transaction
  16722.  
  16723.     -- SUCCESS
  16724.     return (0) -- sp_dropserver
  16725. go
  16726.  
  16727. ------------------------------ sp_serveroption --------------------------------
  16728.  
  16729. raiserror(15339,-1,-1,'sp_serveroption')
  16730. go
  16731. create procedure sp_serveroption
  16732.     @server        sysname,        -- server name to change
  16733.     @optname    varchar(35),    -- option name to turn on/off
  16734.     @optvalue    nvarchar(128)    -- true or false, on or off, collation name, or timeout value
  16735. as
  16736.     -- VARIABLES
  16737.     SET NOCOUNT ON
  16738.     declare @statvalue      smallint,   -- status bit of option
  16739.             @collationID    int,        -- on disk collation ID of the server
  16740.             @timeout        int,        -- value for setting timeout options
  16741.             @fSet            int,        -- 0 or 1 for setting boolean option
  16742.             @distributor    sysname        -- for checking for multiple dist servers
  16743.  
  16744.     -- DISALLOW USER TRANSACTION
  16745.     set implicit_transactions off
  16746.     if @@trancount > 0
  16747.     begin
  16748.         raiserror(15002,-1,-1,'sp_serveroption')
  16749.         return (1)
  16750.     end
  16751.  
  16752.     -- CHECK PERMISSIONS
  16753.     if not (is_srvrolemember('setupadmin') = 1)
  16754.     begin
  16755.         raiserror(15247,-1,-1)
  16756.         return (1)
  16757.     end
  16758.  
  16759.     -- RESOLVE SERVER NAME
  16760.     IF NOT EXISTS (SELECT * FROM master.dbo.sysservers WHERE srvname = @server)
  16761.     BEGIN
  16762.         raiserror(15015,-1,-1,@server)
  16763.         return (1)
  16764.     END
  16765.  
  16766.     -- HANDLE VARIOUS OPTIONS
  16767.     SELECT @optname = lower(@optname), @optvalue = lower(@optvalue)
  16768.  
  16769.     IF @optname = 'collation name'
  16770.     BEGIN
  16771.         -- Collation Name: May reset by string 'null' or NULL value
  16772.         IF @optvalue IS NULL OR @optvalue = 'null'
  16773.             OR COLLATIONPROPERTY(@optvalue, 'collationid') IS NOT NULL
  16774.         BEGIN
  16775.             SELECT @collationID = convert(int, COLLATIONPROPERTY(@optvalue, 'collationid'))
  16776.             if @optvalue is NOT NULL
  16777.                 BEGIN
  16778.                 if convert(int, COLLATIONPROPERTY(@optvalue, 'isunicodeonly')) = 1
  16779.                     BEGIN
  16780.                     raiserror(15301, -1, -1, @optvalue)
  16781.                     return (1)
  16782.                     END
  16783.                 if convert(int, COLLATIONPROPERTY(@optvalue, 'issupportedbyos')) = 0
  16784.                     BEGIN
  16785.                     raiserror(15394, -1, -1, @optvalue)
  16786.                     return (1)
  16787.                     END
  16788.                 END
  16789.             UPDATE master.dbo.sysservers SET srvcollation = @collationID,
  16790.                 -- Turn 'collation compatible' off when srvcollation NOT NULL
  16791.                 srvstatus = CASE WHEN @collationID IS NOT NULL THEN (srvstatus & ~256) ELSE srvstatus END,
  16792.                 schemadate = getdate() WHERE srvname = @server
  16793.             RETURN 0
  16794.         END
  16795.     END
  16796.     ELSE IF @optname IN ('connect timeout','query timeout')
  16797.     BEGIN
  16798.         -- TIMEOUT OPTIONS: Value must be integer-numeric >= 0
  16799.         IF ISNUMERIC (@optvalue) = 1 AND convert(int, @optvalue) >= 0
  16800.         BEGIN
  16801.             SELECT @timeout = convert (int, @optvalue)
  16802.             IF @optname = 'connect timeout'
  16803.                 UPDATE master.dbo.sysservers SET connecttimeout = @timeout,
  16804.                     schemadate = getdate() WHERE srvname = @server
  16805.             ELSE
  16806.                 UPDATE master.dbo.sysservers SET querytimeout = @timeout,
  16807.                     schemadate = getdate() WHERE srvname = @server
  16808.             RETURN 0
  16809.         END
  16810.     END
  16811.     ELSE
  16812.     BEGIN
  16813.         -- BIT-VALUED OPTION: GET STATUS BIT AND WHETHER TO SET OR CLEAR --
  16814.         -- NOTE: CANNOT MAKE A SYSTEM SERVER INTO NON-SYSTEM --
  16815.         SELECT @statvalue = number FROM master.dbo.spt_values WHERE name = @optname and type = 'A'
  16816.         SELECT @fSet = CASE WHEN @optvalue IN ('true','on') THEN 1
  16817.                 WHEN @optvalue IN ('false','off') AND @optname <> 'system' THEN 0
  16818.                 ELSE NULL END
  16819.         IF @statvalue IS NOT NULL AND @fSet IS NOT NULL
  16820.         BEGIN
  16821.             -- ONLY ONE SERVER MAY BE A DISTRIBUTION SERVER
  16822.             IF @optname = 'dist' AND @optvalue in ('true', 'on')
  16823.             BEGIN
  16824.                 SELECT @distributor = srvname from master.dbo.sysservers where (srvstatus & @statvalue) <> 0
  16825.                 IF @distributor is not null
  16826.                 BEGIN
  16827.                     raiserror(14099,-1,-1, @distributor)
  16828.                     RETURN 1
  16829.                 END
  16830.             END
  16831.             ELSE IF @optname = 'lazy schema validation' AND @optvalue in ('true', 'on')
  16832.             BEGIN
  16833.                 IF serverproperty('EngineEdition') <> 3 -- Enterprise edition
  16834.                 BEGIN
  16835.                     raiserror(17050,-1,-1, @optname)
  16836.                     RETURN 1
  16837.                 END
  16838.             END
  16839.             -- DO THE UPDATE
  16840.             UPDATE master.dbo.sysservers SET
  16841.                 srvstatus = (srvstatus & ~@statvalue) | (@statvalue * @fSet),
  16842.                 -- Set srvcollation NULL when turning 'collation compatible' on
  16843.                 srvcollation = CASE WHEN @optname='collation compatible' AND @fSet=1 THEN NULL ELSE srvcollation END,
  16844.                 schemadate = getdate() WHERE srvname = @server
  16845.             RETURN 0
  16846.         END
  16847.     END
  16848.  
  16849.     -- IF WE REACH HERE, WE HAVE AN INVALID PARAMETER
  16850.     raiserror(15600,-1,-1,'sp_serveroption')
  16851.     RETURN 1 -- sp_serveroption
  16852. go
  16853.  
  16854.  
  16855. -------------------------------- sp_addserver ---------------------------------
  16856.  
  16857. raiserror(15339,-1,-1,'sp_addserver')
  16858. go
  16859. create procedure sp_addserver
  16860.     @server         sysname,            --server name
  16861.     @local          varchar(10) = NULL, -- NULL or 'local'
  16862.     @duplicate_ok   varchar(13) = NULL  -- NULL or 'duplicate_ok'
  16863. as
  16864.     -- VARS
  16865.     declare @retcode        int
  16866.  
  16867.     -- CHECK IF SERVER ALREADY EXISTS
  16868.     if exists (select * from master.dbo.sysservers where srvname = @server)
  16869.     begin
  16870.         if @duplicate_ok = 'duplicate_ok'
  16871.             return (0)
  16872.         raiserror(15028,-1,-1,@server)
  16873.         return (1)
  16874.     end
  16875.  
  16876.     -- VALIDATE @local PARAMETER
  16877.     if @local is not null
  16878.     begin
  16879.         select @local = lower(@local)
  16880.         if @local <> 'local'
  16881.         begin
  16882.             raiserror(15379,-1,-1,@local)
  16883.             return (1)
  16884.         end
  16885.  
  16886.         -- ERROR IF ALREADY HAVE A LOCAL SERVER NAME
  16887.         if exists (select * from master.dbo.sysservers where srvid = 0)
  16888.         begin
  16889.             raiserror(15090,-1,-1)
  16890.             return (1)
  16891.         end
  16892.     end
  16893.  
  16894.     -- ADD THE SERVER (CHECKS PERMISSIONS, ETC)
  16895.     execute @retcode = sp_addlinkedserver @server
  16896.     if @retcode <> 0
  16897.         return @retcode
  16898.  
  16899.     -- SET THE SERVER ID IF LOCAL OPTION SPECIFIED
  16900.     if @local = 'local'
  16901.     begin
  16902.         declare @srvid smallint
  16903.         -- UPDATE DEFAULT MAPPING CREATED BY sp_addlinkedserver
  16904.         select @srvid = srvid from master.dbo.sysservers where srvname = @server
  16905.         update master.dbo.sysxlogins set srvid = 0 where srvid = @srvid
  16906.         update master.dbo.sysservers
  16907.             set srvid = 0,
  16908.                 schemadate = getdate()
  16909.             where srvname = @server
  16910.     end
  16911.  
  16912.     -- FOR COMPATIBILITY, TURN OFF THE data access SERVER OPTION
  16913.     execute @retcode = sp_serveroption @server, 'data access', 'off'
  16914.     if @retcode <> 0
  16915.         return @retcode
  16916.  
  16917.     --SET 'local login mapping', 'off' (make rpc-s behave as in 6.5)
  16918.     update master.dbo.sysservers
  16919.     set srvstatus = srvstatus & ~32, schemadate = getdate()
  16920.             where srvname = @server
  16921.  
  16922.     -- SUCCESS
  16923.     return (0) -- sp_addserver
  16924. go
  16925.  
  16926.  
  16927. ------------------------------- sp_setnetname ---------------------------------
  16928.  
  16929. raiserror(15339,-1,-1,'sp_setnetname')
  16930. go
  16931. create procedure sp_setnetname  --- 1995/12/22 13:07
  16932.      @server    sysname    -- server name
  16933.     ,@netname    sysname    -- new net name
  16934. as
  16935.     DECLARE @srvproduct     nvarchar(128)   -- product name; must be SQL Server
  16936.     DECLARE @srvstatus int
  16937.  
  16938.     -- DISALLOW USER TRANSACTION
  16939.     set implicit_transactions off
  16940.     if @@trancount > 0
  16941.     begin
  16942.         raiserror(15002,-1,-1,'sp_setnetname')
  16943.         return (1)
  16944.     end
  16945.  
  16946.     -- CHECK PERMISSIONS
  16947.     if not (is_srvrolemember('setupadmin') = 1)
  16948.     begin
  16949.         raiserror(15247,-1,-1)
  16950.         return (1)
  16951.     end
  16952.  
  16953.     -- CHECK SERVER NAME (MUST BE A SQL SERVER!)
  16954.     select @srvproduct = srvproduct, @srvstatus = srvstatus from master.dbo.sysservers
  16955.                    where srvname = @server
  16956.  
  16957.     if @srvproduct is NULL
  16958.     begin
  16959.         raiserror(15015,-1,-1,@server)
  16960.         return (1)
  16961.     end
  16962.     -- case checking is performed at sp_addlinkedserver so direct comparison is OK here
  16963.     else if @srvproduct <> N'SQL Server'
  16964.     begin
  16965.         raiserror(15576,-1,-1,@server)
  16966.         return (1)
  16967.     end
  16968.  
  16969.     -- CHECK FOR LOOPBACK SERVER AND ISSUE WARNING
  16970.     -- Only check linked server for "data access" since that's where the limitation
  16971.     -- lies.  Replication calls this code although only for RPC servers, so they
  16972.     -- shouldn't be seeing this message
  16973.     if @netname = @@SERVERNAME and @srvstatus & 128 = 128 and @server <> @netname
  16974.     begin
  16975.         raiserror(15577,-1,-1)
  16976.     end
  16977.  
  16978.     -- DO THE UPDATE
  16979.     update master.dbo.sysservers set datasource = @netname, schemadate = getdate()
  16980.         where srvname = @server
  16981.  
  16982.     -- SUCCESS
  16983.     return (0) -- sp_setnetname
  16984. go
  16985.  
  16986. ------------------------------- sp_helpserver ---------------------------------
  16987.  
  16988. raiserror(15339,-1,-1,'sp_helpserver')
  16989. go
  16990. create procedure sp_helpserver
  16991.     @server         sysname = NULL,         -- server name
  16992.     @optname        varchar(35) = NULL,     -- option name to limit results
  16993.     @show_topology  varchar(1) = NULL       -- 't' to show topology coordinates
  16994. as
  16995.     -- PRELIMINARY
  16996.     set nocount on
  16997.     declare @optbit     int,
  16998.             @bitdesc    sysname,
  16999.             @curbit     int
  17000.  
  17001.     -- CHECK IF REQUESTED SERVER(S) EXIST
  17002.     if not exists (select * from master.dbo.sysservers where
  17003.         (@server is null or srvname = @server))
  17004.     begin
  17005.         if @server is null
  17006.             raiserror(15205,-1,-1)
  17007.         else
  17008.             raiserror(15015,-1,-1,@server)
  17009.         return (1)
  17010.     end
  17011.  
  17012.     -- GET THE BIT VALUE(S) FOR THE OPTION REQUESTED
  17013.     if @optname is not null
  17014.     begin
  17015.         select @optbit = number from master.dbo.spt_values
  17016.             where type = 'A' and name = @optname
  17017.         if @optbit is null
  17018.         begin
  17019.             raiserror(15206,-1,-1,@optname)
  17020.             return(1)
  17021.         end
  17022.     end
  17023.     else
  17024.         select @optbit = -1     -- 0xffffffff
  17025.  
  17026.     -- MAKE WORK COPY OF RELEVANT PART OF SYSSERVERS
  17027.     select name = srvname, network = srvnetname, status = convert(varchar(100), ''),
  17028.             id = srvid, srvstat = srvstatus, topx = topologyx, topy = topologyy,
  17029.             collation_name = convert(sysname, CollationPropertyFromID(srvcollation, 'name')),
  17030.             connect_timeout = connecttimeout, query_timeout = querytimeout
  17031.         into #spt_server
  17032.         from master.dbo.sysservers
  17033.         where (@server is null or srvname = @server) and (@optname is null or srvstatus & @optbit <> 0)
  17034.  
  17035.     -- SET THE STATUS FIELD
  17036.     select @curbit = 1
  17037.     while @curbit < 0x10000 -- bit field is a smallint
  17038.     begin
  17039.         select @bitdesc = null
  17040.         select @bitdesc = name from master.dbo.spt_values
  17041.             where type = 'A' and number = @curbit
  17042.         if @bitdesc is not null
  17043.             update #spt_server set status = status + ',' + @bitdesc where srvstat & @curbit <> 0
  17044.         select @curbit = @curbit * 2
  17045.     end
  17046.  
  17047.     -- SHOW THE RESULT SET
  17048.     if lower(@show_topology) <> 't' or @show_topology is null
  17049.         select name, network_name = substring(network, 1, 28),
  17050.                 status = isnull(substring(status,2,8000),''),
  17051.                 id = convert(char(4), id),
  17052.                 collation_name, connect_timeout, query_timeout
  17053.         from #spt_server order by name
  17054.     else
  17055.         select name, network_name = substring(network, 1, 28),
  17056.                 status = isnull(substring(status,2,8000),''),
  17057.                 id = convert(char(4), id),
  17058.                 collation_name, connect_timeout, query_timeout,
  17059.                 topx, topy
  17060.         from #spt_server order by name
  17061.  
  17062.     -- RETURN SUCCESS
  17063.     return(0) -- sp_helpserver
  17064. go
  17065.  
  17066. ------------------------------- sp_helpserver ---------------------------------
  17067.  
  17068. raiserror(15339,-1,-1,'sp_helplinkedsrvlogin')
  17069. go
  17070. create procedure sp_helplinkedsrvlogin
  17071.     @rmtsrvname        sysname = NULL,
  17072.     @locallogin        sysname = NULL
  17073. as
  17074.     declare    @srvid    smallint,
  17075.             @status    smallint,
  17076.             @ret    int
  17077.  
  17078.     -- CHECK REMOTE SERVER NAME.
  17079.     if @rmtsrvname is not null
  17080.     begin
  17081.         select @srvid = srvid from master.dbo.sysservers where srvname = @rmtsrvname
  17082.         if @srvid is null
  17083.         begin
  17084.         raiserror(15015,-1,-1,@rmtsrvname)
  17085.         return (1)
  17086.         end
  17087.     end
  17088.  
  17089.     -- IF SPECIFIED CHECK LOCAL USER NAME
  17090.     if (@locallogin IS NOT NULL)
  17091.     begin
  17092.         select    u.srvname as [Linked Server],        t.name as [Local Login],
  17093.                 s.selfoutmap as [Is Self Mapping],    s.name as [Remote Login]
  17094.         from master.dbo.sysxlogins s, master.dbo.sysxlogins t, master.dbo.sysservers u
  17095.         where ((@rmtsrvname is null or @rmtsrvname=u.srvname) and u.srvid= s.srvid)
  17096.             and s.ishqoutmap = 1 and s.sid=t.sid
  17097.             and t.name = @locallogin and t.ishqoutmap = 0
  17098.     end
  17099.  
  17100.     if (@locallogin IS  NULL)
  17101.     begin
  17102.         -- Get global mapping (s.sid is NULL) if any
  17103.         select    u.srvname as [Linked server],        NULL as [Local Login],
  17104.             s.selfoutmap as [Is Self Mapping],    s.name as [Remote Login]
  17105.         from master.dbo.sysxlogins s, master.dbo.sysservers u
  17106.         where  ((@rmtsrvname is null or @rmtsrvname=u.srvname)and u.srvid= s.srvid)
  17107.             and s.ishqoutmap = 1 and  s.sid is NULL
  17108.         UNION
  17109.         -- Get specific mappings
  17110.         select    u.srvname as [Linked server],        t.name as [Local Login],
  17111.                 s.selfoutmap as [Is Self Mapping],    s.name as [Remote Login]
  17112.         from master.dbo.sysxlogins s, master.dbo.sysxlogins t, master.dbo.sysservers u
  17113.         where ((@rmtsrvname is null or @rmtsrvname=u.srvname) and u.srvid= s.srvid)
  17114.             and s.ishqoutmap = 1 and s.sid=t.sid and t.ishqoutmap = 0
  17115.         order by u.srvname
  17116.     end
  17117.     -- RETURN SUCCESS
  17118.     return(0) -- sp_helplinkedsrvlogin
  17119. go
  17120.  
  17121. -- GRANT PUBLIC ACCESS --
  17122. grant execute on sp_addlinkedserver to public
  17123. grant execute on sp_dropserver to public
  17124. grant execute on sp_serveroption to public
  17125. grant execute on sp_addserver to public
  17126. grant execute on sp_setnetname to public
  17127. grant execute on sp_helpserver to public
  17128. grant execute on sp_helplinkedsrvlogin to public
  17129. go
  17130. /************************  END-SYSSERVER-STORED-PROCS  ***********************/
  17131.  
  17132. /************************  SYSOLEDBUSERS-STORED-PROCS  ***********************/
  17133. if object_id('sp_addlinkedsrvlogin','P') IS NOT NULL
  17134.     drop procedure sp_addlinkedsrvlogin
  17135. if object_id('sp_droplinkedsrvlogin','P') IS NOT NULL
  17136.     drop procedure sp_droplinkedsrvlogin
  17137. go
  17138.  
  17139. ------------------------------- sp_addlinkedsrvlogin ---------------------------------
  17140.  
  17141. raiserror(15339,-1,-1,'sp_addlinkedsrvlogin')
  17142. go
  17143. create procedure sp_addlinkedsrvlogin
  17144.     @rmtsrvname        sysname,
  17145.     @useself        varchar(8) = 'true',
  17146.     @locallogin        sysname = NULL,
  17147.     @rmtuser        sysname = NULL,
  17148.     @rmtpassword    sysname = NULL
  17149. as
  17150.     declare    @srvid    smallint,
  17151.             @status    smallint,
  17152.             @localsid    varbinary(85),
  17153.             @ret    int
  17154.  
  17155.     -- DISALLOW USER TRANSACTION
  17156.     set implicit_transactions off
  17157.     if @@trancount > 0
  17158.     begin
  17159.         raiserror(15002,-1,-1,'sp_addlinkedsrvlogin')
  17160.         return (1)
  17161.     end
  17162.  
  17163.     -- CHECK PERMISSIONS
  17164.     if not (is_srvrolemember('securityadmin') = 1)
  17165.     begin
  17166.         raiserror(15247,-1,-1)
  17167.         return (1)
  17168.     end
  17169.  
  17170.     -- VALIDATE @useself PARAMETER --
  17171.     select @useself = lower(@useself)
  17172.     if @useself is null or @useself not in ('true','false')
  17173.     begin
  17174.         raiserror(15600,-1,-1,'sp_addlinkedsrvlogin')
  17175.         return 1
  17176.     end
  17177.  
  17178.     -- CHECK REMOTE SERVER NAME.
  17179.     select @srvid = srvid from master.dbo.sysservers where srvname = @rmtsrvname
  17180.     if @srvid is null
  17181.     begin
  17182.         raiserror(15015,-1,-1,@rmtsrvname)
  17183.         return (1)
  17184.     end
  17185.  
  17186.     -- IF SPECIFIED CHECK LOCAL USER NAME
  17187.     if (@locallogin IS NOT NULL)
  17188.     begin
  17189.         select @localsid = sid from master.dbo.syslogins where loginname = @locallogin
  17190.         if @localsid IS NULL
  17191.         begin
  17192.             -- ADD ROW FOR NT LOGIN IF NEEDED --
  17193.             execute @ret = sp_MSaddlogin_implicit_ntlogin @locallogin
  17194.             if (@ret = 0)
  17195.                 select @localsid = sid from master.dbo.syslogins where loginname = @locallogin
  17196.             if (@localsid IS NULL)
  17197.             begin
  17198.                 raiserror(15067,-1,-1,@locallogin)
  17199.                 return (1)
  17200.             end
  17201.         end
  17202.     end
  17203.  
  17204.     -- 64 IMPLIES sysxlogins::ishqoutmap is TRUE
  17205.     select @status = 64
  17206.  
  17207.     -- IF @useself IS TRUE IT OVERRIDES PARAMETERS @rmtuser, and @rmtpassword
  17208.     if @useself = 'true'
  17209.     begin
  17210.         select @rmtuser = NULL
  17211.         select @rmtpassword = NULL
  17212.         select @status = @status | 128
  17213.     end
  17214.  
  17215.     BEGIN TRAN
  17216.  
  17217.     -- DELETE EXISTING MAPPING(s) FOR THIS @sid
  17218.     update master.dbo.sysxlogins set xstatus = xstatus & ~192
  17219.         where srvid = @srvid AND ishqoutmap = 1 AND isrpcinmap = 1
  17220.             AND ((sid IS NULL AND @localsid IS NULL) OR sid = @localsid)
  17221.     if @@rowcount = 0
  17222.         delete master.dbo.sysxlogins where srvid = @srvid AND ishqoutmap = 1
  17223.             AND ((sid IS NULL AND @localsid IS NULL) OR sid = @localsid)
  17224.  
  17225.     -- ATTEMPT TO TAG THIS ONTO EXISTING ROW --
  17226.     update master.dbo.sysxlogins
  17227.         set xstatus = (xstatus & ~192) | @status,
  17228.             xdate2 = getdate(),
  17229.             password = convert(varbinary(256), encrypt(@rmtpassword))
  17230.         where srvid = @srvid AND isrpcinmap = 1
  17231.             AND ((sid IS NULL AND @localsid IS NULL) OR sid = @localsid)
  17232.             AND ((name IS NULL AND @rmtuser IS NULL) OR name = @rmtuser)
  17233.  
  17234.     -- IF NO ROW UPDATED, INSERT NEW ROW --
  17235.     if (@@rowcount = 0)
  17236.         insert master.dbo.sysxlogins values
  17237.                 (@srvid, @localsid, @status, getdate(), getdate(), @rmtuser,
  17238.                        convert(varbinary(256), encrypt(@rmtpassword)), 0, NULL)
  17239.  
  17240.     COMMIT TRAN
  17241.  
  17242.     -- RETURN SUCCESS
  17243.     return(0) -- sp_addlinkedsrvlogin
  17244. go
  17245.  
  17246. ------------------------------- sp_droplinkedsrvlogin ---------------------------------
  17247.  
  17248. raiserror(15339,-1,-1,'sp_droplinkedsrvlogin')
  17249. go
  17250. create procedure sp_droplinkedsrvlogin
  17251.     @rmtsrvname        sysname,
  17252.     @locallogin        sysname
  17253. as
  17254.     declare @srvid    smallint
  17255.     declare @localsid    varbinary(85)
  17256.  
  17257.     -- DISALLOW USER TRANSACTION
  17258.     set implicit_transactions off
  17259.     if @@trancount > 0
  17260.     begin
  17261.         raiserror(15002,-1,-1,'sp_droplinkedsrvlogin')
  17262.         return (1)
  17263.     end
  17264.  
  17265.     -- CHECK PERMISSIONS
  17266.     if not (is_srvrolemember('securityadmin') = 1)
  17267.     begin
  17268.         raiserror(15247,-1,-1)
  17269.         return (1)
  17270.     end
  17271.  
  17272.     -- CHECK REMOTE SERVER NAME.
  17273.     select @srvid = srvid from master.dbo.sysservers where srvname = @rmtsrvname
  17274.     if @srvid is null
  17275.     begin
  17276.         raiserror(15015,-1,-1,@rmtsrvname)
  17277.         return (1)
  17278.     end
  17279.  
  17280.     -- CHECK LOCAL USER NAME IF GIVEN
  17281.     if @locallogin is not null
  17282.     begin
  17283.         select @localsid = suser_sid(@locallogin)
  17284.         if (@localsid IS NULL)
  17285.         begin
  17286.             raiserror(15067,-1,-1,@locallogin)
  17287.             return (1)
  17288.         end
  17289.     end
  17290.  
  17291.     -- DELETE MAPPING(s)
  17292.     update master.dbo.sysxlogins set xstatus = xstatus & ~192
  17293.         where srvid = @srvid AND ishqoutmap = 1 AND isrpcinmap = 1
  17294.             AND ((sid IS NULL AND @localsid IS NULL) OR sid = @localsid)
  17295.     if @@rowcount = 0
  17296.         delete master.dbo.sysxlogins where srvid = @srvid AND ishqoutmap = 1
  17297.             AND ((sid IS NULL AND @localsid IS NULL) OR sid = @localsid)
  17298.  
  17299.     -- RETURN SUCCESS
  17300.     return(0) -- sp_droplinkedsrvlogin
  17301. go
  17302.  
  17303. -- GRANT PUBLIC ACCESS --
  17304. grant execute on sp_addlinkedsrvlogin to public
  17305. grant execute on sp_droplinkedsrvlogin to public
  17306. go
  17307. /************************  END-SYSOLEDBUSERS-STORED-PROCS  ***********************/
  17308.  
  17309. /******************************************************************************
  17310. ****************************  FULLTEXT INDEXES ********************************
  17311. ******************************************************************************/
  17312. checkpoint
  17313. go
  17314. if object_id('sp_fulltext_service','P') IS NOT NULL
  17315.     drop procedure sp_fulltext_service
  17316. if object_id('sp_fulltext_database','P') IS NOT NULL
  17317.     drop procedure sp_fulltext_database
  17318. if object_id('sp_fulltext_catalog','P') IS NOT NULL
  17319.     drop procedure sp_fulltext_catalog
  17320. if object_id('sp_fulltext_table','P') IS NOT NULL
  17321.     drop procedure sp_fulltext_table
  17322. if object_id('sp_fulltext_column','P') IS NOT NULL
  17323.     drop procedure sp_fulltext_column
  17324.     if object_id('sp_help_fulltext_catalogs','P') IS NOT NULL
  17325.     drop procedure sp_help_fulltext_catalogs
  17326. if object_id('sp_help_fulltext_catalogs_cursor','P') IS NOT NULL
  17327.     drop procedure sp_help_fulltext_catalogs_cursor
  17328. if object_id('sp_help_fulltext_tables','P') IS NOT NULL
  17329.     drop procedure sp_help_fulltext_tables
  17330. if object_id('sp_help_fulltext_tables_cursor','P') IS NOT NULL
  17331.     drop procedure sp_help_fulltext_tables_cursor
  17332. if object_id('sp_help_fulltext_columns','P') IS NOT NULL
  17333.     drop procedure sp_help_fulltext_columns
  17334. if object_id('sp_help_fulltext_columns_cursor','P') IS NOT NULL
  17335.     drop procedure sp_help_fulltext_columns_cursor
  17336. if object_id('sp_fulltext_getdata','X') IS NOT NULL
  17337.     exec sp_dropextendedproc 'sp_fulltext_getdata'
  17338. execute sp_addextendedproc 'sp_fulltext_getdata','(server internal)'
  17339. go
  17340.  
  17341.  
  17342. ---------------------------- sp_fulltext_service ------------------------------
  17343.  
  17344. raiserror(15339,-1,-1,'sp_fulltext_service')
  17345. go
  17346. create proc sp_fulltext_service
  17347.     @action     varchar(20),    -- resource_usage | clean_up | connect_timeout | data_timeout
  17348.     @value      int = NULL      -- value for resource_usage | connect_timeout | data_timeout
  17349. as
  17350.     -- VALIDATE PARAMS --
  17351.     if @action is null OR @action not in ('resource_usage', 'clean_up', 'connect_timeout', 'data_timeout')
  17352.         OR (@value is not null AND @action not in ('resource_usage', 'connect_timeout', 'data_timeout'))
  17353.         OR (@value is null and @action in ('resource_usage', 'connect_timeout', 'data_timeout'))
  17354.     begin
  17355.         raiserror(15600,-1,-1,'sp_fulltext_service')
  17356.         return 1
  17357.     end
  17358.  
  17359.     -- DISALLOW USER TRANSACTION --
  17360.     set implicit_transactions off
  17361.     if @@trancount > 0
  17362.     begin
  17363.         raiserror(15002,-1,-1,'sp_fulltext_service')
  17364.         return 1
  17365.     end
  17366.  
  17367.     -- CHECK PERMISSIONS (must be serveradmin) --
  17368.     if (is_srvrolemember('serveradmin') = 0)
  17369.     begin
  17370.         raiserror(15247,-1,-1)
  17371.         return 1
  17372.     end
  17373.  
  17374.     if @action = 'resource_usage'
  17375.     begin
  17376.         DBCC CALLFULLTEXT ( 13, @value )  -- FTSetResource( @value )
  17377.         if @@error <> 0
  17378.             return 1
  17379.     end
  17380.  
  17381.     if @action = 'clean_up'
  17382.     begin
  17383.         DBCC CALLFULLTEXT ( 8 )    -- Iterate thru catalogs, remove if dbid doesn't exist.
  17384.         if @@error <> 0
  17385.             return 1
  17386.     end
  17387.  
  17388.     if @action = 'connect_timeout'
  17389.     begin
  17390.         DBCC CALLFULLTEXT ( 14, @value )    -- SetProperty( FT_PROP_CONN_TIMEOUT,  @value )
  17391.         if @@error <> 0
  17392.             return 1
  17393.     end
  17394.  
  17395.     if @action = 'data_timeout'
  17396.     begin
  17397.         DBCC CALLFULLTEXT ( 15, @value )    -- SetProperty( FT_PROP_DATA_TIMEOUT,  @value )
  17398.         if @@error <> 0
  17399.             return 1
  17400.     end
  17401.  
  17402.  
  17403.     -- SUCCESS --
  17404.     return 0    -- sp_fulltext_service
  17405. go
  17406.  
  17407. ---------------------------- sp_fulltext_database -----------------------------
  17408.  
  17409. raiserror(15339,-1,-1,'sp_fulltext_database')
  17410. go
  17411. create proc sp_fulltext_database
  17412.     @action        varchar(20)        -- 'enable' | 'disable'
  17413. as
  17414.     declare @ftcat        sysname,
  17415.             @ftcatid    smallint,
  17416.             @path        nvarchar(260),
  17417.             @objid        int,
  17418.             @dbid        smallint,
  17419.             @objname    sysname
  17420.  
  17421.     -- VALIDATE PARAMS --
  17422.     if @action is null OR @action not in ('enable','disable')
  17423.     begin
  17424.         raiserror(15600,-1,-1,'sp_fulltext_database')
  17425.         return 1
  17426.     end
  17427.  
  17428.     -- DISALLOW USER TRANSACTION --
  17429.     set implicit_transactions off
  17430.     if @@trancount > 0
  17431.     begin
  17432.         raiserror(15002,-1,-1,'sp_fulltext_database')
  17433.         return 1
  17434.     end
  17435.  
  17436.     -- CHECK PERMISSIONS (must be a dbowner) --
  17437.     if (is_member('db_owner') = 0)
  17438.     begin
  17439.         raiserror(15247,-1,-1)
  17440.         return 1
  17441.     end
  17442.  
  17443.     -- CHECK DATABASE MODE (must not be read-only) --
  17444.     if (DATABASEPROPERTY(db_name(), 'IsReadOnly') = 1)
  17445.     begin
  17446.         raiserror(15635, -1, -1, 'sp_fulltext_database')
  17447.         return 1
  17448.     end
  17449.  
  17450.     -- CLEAR SYSDATABASES BIT AND PROPAGATE W/ CHECKPOINT (for both enable & disable) --
  17451.     select @dbid = db_id()
  17452.     update master.dbo.sysdatabases set status2 = status2 & ~536870912 where dbid = @dbid
  17453.     checkpoint
  17454.  
  17455.     -- DROP ALL CATALOGS WITH THIS DATABASE (for both enable/disable) --
  17456.     DBCC CALLFULLTEXT ( 7, @dbid )    -- FTDropAllCatalogs ( "@dbid" )
  17457.     if @@error <> 0
  17458.         return 1
  17459.  
  17460.     -- DELETE ALL THE CHANGE NOTIFICATIONS FROM SYSFULLTEXTNOTIFY --
  17461.     delete sysfulltextnotify
  17462.  
  17463.     if @action = 'enable'
  17464.     begin
  17465.         -- CREATE CATALOGS --
  17466.         declare ms_crs_ftcat cursor static local for select name, path from sysfulltextcatalogs
  17467.         open ms_crs_ftcat
  17468.         fetch ms_crs_ftcat into @ftcat, @path
  17469.         while @@fetch_status >= 0
  17470.         begin
  17471.             DBCC CALLFULLTEXT ( 16, @ftcat, @path )    -- FTCreateCatalog( @ftcatid, @path )
  17472.             if @@error <> 0
  17473.                 return 1
  17474.             fetch ms_crs_ftcat into @ftcat, @path
  17475.         end
  17476.         deallocate ms_crs_ftcat
  17477.  
  17478.         declare    @vc1            nvarchar(517)
  17479.         -- BEGIN TRAN
  17480.         begin tran
  17481.  
  17482.         -- ACTIVATE TABLES/URLs --
  17483.         declare ms_crs_ftind cursor static local for select ftcatid, id from sysobjects
  17484.                     where (ftcatid <> 0)
  17485.  
  17486.         open ms_crs_ftind
  17487.         fetch ms_crs_ftind into @ftcatid, @objid
  17488.         while @@fetch_status >= 0
  17489.         begin
  17490.             DBCC CALLFULLTEXT ( 5, @ftcatid, @objid )    -- FTAddURL( @ftcatid, db_id(), @objid )
  17491.             if @@error <> 0
  17492.                 goto error_abort_exit
  17493.  
  17494.             -- CHECK TABLE FOR NOTIFICATIONS --
  17495.             if ObjectProperty(@objid, 'TableFulltextChangeTrackingOn') = 1
  17496.             begin
  17497.                 -- ERROR IF DATABASE IS IN SINGLE USER MODE --
  17498.                 if DATABASEPROPERTY(db_name(), 'IsSingleUser') = 1
  17499.                 begin
  17500.                     select @objname = object_name(@objid)
  17501.                     raiserror(15638, -1, -1, @objname)
  17502.  
  17503.                     select @vc1 = quotename(user_name(OBJECTPROPERTY(@objid,'OwnerId'))) + '.'
  17504.                         + quotename(@objname)
  17505.  
  17506.                     -- LOCK TABLE --
  17507.                     dbcc lockobjectschema(@vc1)
  17508.                     if @@error <> 0
  17509.                         goto error_abort_exit
  17510.  
  17511.                     -- TURN OFF CHANGE TRACKING ACTIVE BITS IN SYSOBJECTS --
  17512.                     update sysobjects set status = status & ~192 where id = @objid
  17513.  
  17514.                     fetch ms_crs_ftind into @ftcatid, @objid
  17515.                     continue
  17516.                 end
  17517.  
  17518.                 -- START A FULL CRAWL FOR THIS TABLE --
  17519.                 DBCC CALLFULLTEXT ( 12, @ftcatid, @objid, 0 )
  17520.                 if @@error <> 0
  17521.                     goto error_abort_exit
  17522.             end
  17523.  
  17524.             -- CHECK TABLE FOR AUTOPROPAGATION  -
  17525.             if ObjectProperty(@objid, 'TableFulltextBackgroundUpdateIndexOn') = 1
  17526.             begin
  17527.                 DBCC CALLFULLTEXT ( 10, @ftcatid, @objid )    -- FTEnableAutoProp( @ftcatid, db_id(), @objid )
  17528.                 if @@error <> 0
  17529.                     goto error_abort_exit
  17530.             end
  17531.  
  17532.             fetch ms_crs_ftind into @ftcatid, @objid
  17533.         end
  17534.         deallocate ms_crs_ftind
  17535.  
  17536.         -- SET SYSDATABASES BIT --
  17537.         update master.dbo.sysdatabases set status2 = status2 | 536870912 where dbid = @dbid
  17538.  
  17539.         -- COMMIT TRAN --
  17540.         commit tran
  17541.  
  17542.         -- CHECKPOINT TO PUSH SYSDATABASES BIT TO MEMORY --
  17543.         checkpoint
  17544.  
  17545.         if @@error <> 0
  17546.             goto error_abort_exit
  17547.  
  17548.     end
  17549.  
  17550.  
  17551.     -- SUCCESS --
  17552.     return 0    -- sp_fulltext_database
  17553.  
  17554.  
  17555. error_abort_exit:
  17556.     rollback tran
  17557.     return 1    -- sp_fulltext_database
  17558. go
  17559.  
  17560. ---------------------------- sp_fulltext_catalog ------------------------------
  17561.  
  17562. raiserror(15339,-1,-1,'sp_fulltext_catalog')
  17563. go
  17564. create proc sp_fulltext_catalog
  17565.     @ftcat        sysname,        -- full-text catalog name
  17566.     @action     varchar(20),    -- create | drop | | rebuild | ...
  17567.     @path        nvarchar(101) = null    -- optional file path for create (max of 100 chars!!!)
  17568. as
  17569.     declare @objname sysname,
  17570.             @objid    int,
  17571.             @vc1    nvarchar(517),
  17572.             @tabname    nvarchar(517),
  17573.             @tabwarn int
  17574.  
  17575.     select @tabwarn = 0
  17576.  
  17577.     -- FULLTEXT MUST BE ACTIVE IN DATABASE --
  17578.     if DatabaseProperty(db_name(), 'IsFulltextEnabled') = 0
  17579.     begin
  17580.         raiserror(15601,-1,-1)
  17581.         return 1
  17582.     end
  17583.  
  17584.     -- VALIDATE PARAMS --
  17585.     if @action is null
  17586.         OR @action not in ('create','drop','start_full','start_incremental','stop','rebuild')
  17587.         OR @ftcat is null OR len(@ftcat) = 0
  17588.         OR (@path is not null and @action <> 'create')
  17589.         OR (len(@path) > 100 )
  17590.     begin
  17591.         raiserror(15600,-1,-1,'sp_fulltext_catalog')
  17592.         return 1
  17593.     end
  17594.  
  17595.     -- DISALLOW USER TRANSACTION --
  17596.     set implicit_transactions off
  17597.     if @@trancount > 0
  17598.     begin
  17599.         raiserror(15002,-1,-1,'sp_fulltext_catalog')
  17600.         return 1
  17601.     end
  17602.  
  17603.     -- CHECK PERMISSIONS (must be a dbowner) --
  17604.     if (is_member('db_owner') = 0)
  17605.     begin
  17606.         raiserror(15247,-1,-1)
  17607.         return 1
  17608.     end
  17609.  
  17610.     -- CHECK DATABASE MODE (must not be read-only) --
  17611.     if DATABASEPROPERTY(db_name(), 'IsReadOnly') = 1
  17612.     begin
  17613.         raiserror(15635, -1, -1, 'sp_fulltext_catalog')
  17614.         return 1
  17615.     end
  17616.  
  17617.     -- CATALOG MUST EXIST IF NOT CREATING --
  17618.     declare @ftcatid smallint
  17619.     select @ftcatid = ftcatid from sysfulltextcatalogs where name = @ftcat
  17620.     if @action not in ('create', 'drop') and @ftcatid is null
  17621.     begin
  17622.         raiserror(7641,-1,-1,@ftcat)
  17623.         return 1
  17624.     end
  17625.  
  17626.     if @action = 'create'
  17627.     begin
  17628.         DBCC CALLFULLTEXT ( 1, @ftcat, @path )    -- FTCreateCatalog( @ftcat, @path )
  17629.         if @@error <> 0 
  17630.             return 1
  17631.     end
  17632.  
  17633.     if @action = 'drop'
  17634.     begin
  17635.         -- CANNOT DROP CATALOG IF USED --
  17636.         if exists (select * from sysobjects where ftcatid = @ftcatid)
  17637.         begin
  17638.             raiserror(15604,-1,-1, @ftcat)
  17639.             return 1
  17640.         end
  17641.  
  17642.         DBCC CALLFULLTEXT ( 2, @ftcat )    -- FTDropCatalog( @ftcat )
  17643.         if @@error <> 0
  17644.             return 1
  17645.     end
  17646.  
  17647.     if @action = 'start_full'
  17648.     begin
  17649.         -- ERROR IF DATABASE IS IN SINGLE USER MODE --
  17650.         if DATABASEPROPERTY(db_name(), 'IsSingleUser') = 1
  17651.         begin
  17652.             raiserror(15636, -1, -1, @ftcat)
  17653.             return 1
  17654.         end
  17655.  
  17656.         begin tran
  17657.         -- MARK TABLES/URLs AS --
  17658.         declare ms_crs_ftind cursor static local for select id, name from sysobjects
  17659.                     where ftcatid = @ftcatid
  17660.         open ms_crs_ftind
  17661.         fetch ms_crs_ftind into @objid, @tabname
  17662.         while @@fetch_status >= 0
  17663.         begin
  17664.  
  17665.             -- ERROR ON TABLE IF TABLE IS NOT ACTIVATED --
  17666.             if (ObjectProperty(@objid, 'TableHasActiveFulltextIndex') = 0)
  17667.             begin
  17668.                 raiserror(15630, -1, -1, @tabname)
  17669.                 goto error_exit
  17670.             end
  17671.  
  17672.             -- SKIP TABLE IF CRAWL ALREADY IN PROGRESS --
  17673.             if (ObjectProperty(@objid, 'TableFulltextPopulateStatus') != 0)
  17674.             begin
  17675.                 select @tabwarn = 1
  17676.                 fetch ms_crs_ftind into @objid, @tabname
  17677.                 continue
  17678.             end
  17679.  
  17680.  
  17681.             -- START FULL CRAWL
  17682.             DBCC CALLFULLTEXT ( 12, @ftcatid, @objid, 0 )
  17683.             if @@error <> 0    -- server raised an error
  17684.             begin
  17685.                 -- server did an ex_raise - this is unreachable code
  17686.                 goto error_exit
  17687.             end
  17688.  
  17689.             -- DELETE NOTIFICATIONS FROM SYSFULLTEXTNOTIFY --
  17690.             delete sysfulltextnotify where tableid = @objid
  17691.  
  17692.             if (ObjectProperty(@objid, 'TableIsFulltextSchemaModified') = 1)
  17693.             and (ObjectProperty(@objid, 'TableFulltextChangeTrackingOn') = 0)
  17694.             begin
  17695.  
  17696.                 select @vc1 = quotename(user_name(OBJECTPROPERTY(@objid,'OwnerId'))) + '.'
  17697.                             + quotename(object_name(@objid))
  17698.  
  17699.                 dbcc lockobjectschema(@vc1)
  17700.  
  17701.                 update sysobjects set status = status & ~128 where id = @objid
  17702.  
  17703.             end
  17704.  
  17705.             fetch ms_crs_ftind into @objid, @tabname
  17706.         end
  17707.         deallocate ms_crs_ftind
  17708.  
  17709.         commit tran
  17710.  
  17711.     end
  17712.  
  17713.     if @action = 'start_incremental'
  17714.     begin
  17715.         -- ERROR IF DATABASE IS IN SINGLE USER MODE --
  17716.         if DATABASEPROPERTY(db_name(), 'IsSingleUser') = 1
  17717.         begin
  17718.             raiserror(15636, -1, -1, @ftcat)
  17719.             return 1
  17720.         end
  17721.         begin tran
  17722.  
  17723.         -- MARK TABLES/URLs AS --
  17724.         declare ms_crs_ftind cursor static local for select id, name from sysobjects
  17725.                     where ftcatid = @ftcatid
  17726.         open ms_crs_ftind
  17727.         fetch ms_crs_ftind into @objid, @tabname
  17728.         while @@fetch_status >= 0
  17729.         begin
  17730.             -- ERROR ON TABLE IF TABLE IS NOT ACTIVATED --
  17731.             if (ObjectProperty(@objid, 'TableHasActiveFulltextIndex') = 0)
  17732.             begin
  17733.                 raiserror(15630, -1, -1, @tabname)
  17734.                 goto error_exit
  17735.             end
  17736.  
  17737.             -- SKIP TABLE IF CRAWL ALREADY IN PROGRESS --
  17738.             if (ObjectProperty(@objid, 'TableFulltextPopulateStatus') != 0)
  17739.             begin
  17740.                 select @tabwarn = 1
  17741.                 fetch ms_crs_ftind into @objid, @tabname
  17742.                 continue
  17743.             end
  17744.  
  17745.             if (ObjectProperty(@objid, 'TableIsFulltextSchemaModified') = 1)
  17746.             and (ObjectProperty(@objid, 'TableFulltextChangeTrackingOn') = 0)
  17747.             begin
  17748.  
  17749.                 -- START A FULL POPULATION FOR THIS TABLE --
  17750.                 DBCC CALLFULLTEXT ( 12, @ftcatid, @objid, 0 )
  17751.                 if @@error <> 0
  17752.                 begin
  17753.                     -- server did an ex_raise - this is unreachable code --
  17754.                     goto error_exit
  17755.                 end
  17756.  
  17757.                 select @vc1 = quotename(user_name(OBJECTPROPERTY(@objid,'OwnerId'))) + '.'
  17758.                         + quotename(object_name(@objid))
  17759.  
  17760.                 dbcc lockobjectschema(@vc1)
  17761.  
  17762.                 update sysobjects set status = status & ~128 where id = @objid
  17763.  
  17764.             end
  17765.             else
  17766.             begin
  17767.                 -- START AN INCREMENTAL POPULATION FOR THIS TABLE --
  17768.                 DBCC CALLFULLTEXT ( 12, @ftcatid, @objid, 1 )
  17769.                 if @@error <> 0
  17770.                 begin
  17771.                     -- server did an ex_raise - this is unreachable code --
  17772.                     goto error_exit
  17773.                 end
  17774.  
  17775.             end
  17776.  
  17777.             -- DELETE NOTIFICATIONS FROM SYSFULLTEXTNOTIFY --
  17778.             delete sysfulltextnotify where tableid = @objid
  17779.  
  17780.             fetch ms_crs_ftind into @objid, @tabname
  17781.         end
  17782.         deallocate ms_crs_ftind
  17783.         commit tran
  17784.  
  17785.  
  17786.     end
  17787.  
  17788.     if @action = 'stop'
  17789.     begin
  17790.         declare ms_crs_ftind cursor static local for select id, name from sysobjects
  17791.                     where ftcatid = @ftcatid
  17792.         open ms_crs_ftind
  17793.         fetch ms_crs_ftind into @objid, @tabname
  17794.         while @@fetch_status >= 0
  17795.         begin
  17796.  
  17797.             -- ERROR ON TABLE IF TABLE IS NOT ACTIVATED --
  17798.             if ObjectProperty(@objid, 'TableHasActiveFulltextIndex') = 0
  17799.             begin
  17800.                 raiserror(15630, -1, -1, @tabname)
  17801.                 return 1
  17802.             end
  17803.  
  17804.             -- SKIP TABLE IF CRAWL ALREADY STOPPED - NO WARNING --
  17805.             if (ObjectProperty(@objid, 'TableFulltextPopulateStatus') = 0)
  17806.             begin
  17807.                 fetch ms_crs_ftind into @objid, @tabname
  17808.                 continue
  17809.             end
  17810.  
  17811.             -- ERROR IF POPULATE STATUS OF THE TABLE IS CRAWLING AND CT ON
  17812.             if (ObjectProperty(@objid, 'TableFulltextChangeTrackingOn') = 1)
  17813.             and ((ObjectProperty(@objid, 'TableFulltextPopulateStatus') = 1)
  17814.             or (ObjectProperty(@objid, 'TableFulltextPopulateStatus') = 2))
  17815.             begin
  17816.                 raiserror(15642,-1,-1, @tabname)
  17817.                 return 1
  17818.             end
  17819.  
  17820.             -- STOP A FULL/INCREMENTAL POPULATION FOR THIS TABLE --
  17821.             DBCC CALLFULLTEXT ( 12, @ftcatid, @objid, 2 )
  17822.             if @@error <> 0
  17823.             begin
  17824.                 -- server did an ex_raise - this is unreachable code --
  17825.                 return 1
  17826.             end
  17827.  
  17828.             fetch ms_crs_ftind into @objid, @tabname
  17829.         end
  17830.         deallocate ms_crs_ftind
  17831.  
  17832.     end
  17833.  
  17834.     if @action = 'rebuild'
  17835.     begin
  17836.  
  17837.         -- RE-CREATE CATALOG (Will first drop)
  17838.         select @path = path from sysfulltextcatalogs where ftcatid = @ftcatid
  17839.         DBCC CALLFULLTEXT ( 16, @ftcat, @path )    -- FTCreateCatalog( @ftcat, @path )
  17840.         if @@error <> 0
  17841.         begin 
  17842.             -- server did an ex_raise - this is unreachable code --
  17843.             return 1
  17844.         end
  17845.  
  17846.         begin tran
  17847.  
  17848.         -- RE-ACTIVATE TABLES/URLs --
  17849.         declare ms_crs_ftind cursor static local for select id from sysobjects
  17850.                     where ftcatid = @ftcatid
  17851.         open ms_crs_ftind
  17852.         fetch ms_crs_ftind into @objid
  17853.         while @@fetch_status >= 0
  17854.         begin
  17855.             DBCC CALLFULLTEXT ( 5, @ftcatid, @objid )    -- FTAddURL( @ftcat, db_id(), @objid )
  17856.             if @@error <> 0
  17857.             begin
  17858.                 -- server did an ex_raise - this is unreachable code --
  17859.                 goto error_exit
  17860.             end
  17861.  
  17862.             -- CHECK TABLE FOR NOTIFICATIONS --
  17863.             if ObjectProperty(@objid, 'TableFulltextChangeTrackingOn') = 1
  17864.                 and ObjectProperty(@objid, 'TableHasActiveFulltextIndex') = 1
  17865.             begin
  17866.                 -- ERROR IF DATABASE IS IN SINGLE USER MODE --
  17867.                 if DATABASEPROPERTY(db_name(), 'IsSingleUser') = 1
  17868.                 begin
  17869.                     select @objname = object_name(@objid)
  17870.                     raiserror(15638, -1, -1, @objname)
  17871.  
  17872.                     select @vc1 = quotename(user_name(OBJECTPROPERTY(@objid,'OwnerId'))) + '.'
  17873.                         + quotename(@objname)
  17874.  
  17875.  
  17876.                     dbcc lockobjectschema(@vc1)
  17877.  
  17878.                     -- DISABLE FULLTEXT AUTO PROPAGATION (NO ERROR IF ALREADY DISABLED AND --
  17879.                     -- IGNORE ANY OTHER ERRORS) --
  17880.                     DBCC CALLFULLTEXT ( 9, @objid )    -- FTDisableNotify( db_id(), @objid )
  17881.                     if @@error <> 0
  17882.                     begin
  17883.                         -- server did an ex_raise - this is unreachable code --
  17884.                         goto error_exit
  17885.                     end
  17886.  
  17887.                     -- TURN OFF CHANGE TRACKING ACTIVE BITS IN SYSOBJECTS --
  17888.                     update sysobjects set status = status & ~192 where id = @objid
  17889.  
  17890.                     fetch ms_crs_ftind into @objid
  17891.                     continue
  17892.                 end
  17893.  
  17894.                 -- STOP A FULL/INCREMENTAL POPULATION FOR THIS TABLE --
  17895.                 DBCC CALLFULLTEXT ( 12, @ftcatid, @objid, 2 )
  17896.                 if @@error <> 0
  17897.                 begin
  17898.                     -- server did an ex_raise - this is unreachable code --
  17899.                     goto error_exit
  17900.                 end
  17901.  
  17902.                 -- START A FULL CRAWL FOR THIS TABLE --
  17903.                 DBCC CALLFULLTEXT ( 12, @ftcatid, @objid, 0 )
  17904.                 if @@error <> 0
  17905.                 begin
  17906.                     -- server did an ex_raise - this is unreachable code --
  17907.                     goto error_exit
  17908.                 end
  17909.  
  17910.                 -- DELETE NOTIFICATIONS FROM SYSFULLTEXTNOTIFY --
  17911.                 delete sysfulltextnotify where tableid = @objid
  17912.  
  17913.             end
  17914.  
  17915.             -- CHECK TABLE FOR AUTOPROPAGATION  -
  17916.             if ObjectProperty(@objid, 'TableFulltextAutoPropagationOn') = 1
  17917.                 and ObjectProperty(@objid, 'TableHasActiveFulltextIndex') = 1
  17918.             begin
  17919.                 DBCC CALLFULLTEXT ( 10, @ftcatid, @objid )    -- FTEnableAutoProp( @ftcatid, db_id(), @objid )
  17920.                 if @@error <> 0
  17921.                 begin
  17922.                     -- server did an ex_raise - this is unreachable code --
  17923.                     goto error_exit
  17924.                 end
  17925.             end
  17926.  
  17927.             fetch ms_crs_ftind into @objid
  17928.         end
  17929.         deallocate ms_crs_ftind
  17930.  
  17931.         commit tran
  17932.  
  17933.     end
  17934.     if(@tabwarn <> 0)
  17935.     begin
  17936.         raiserror(15643, -1, -1)
  17937.         return 0
  17938.     end
  17939.     return 0    -- sp_fulltext_catalog
  17940.  
  17941. error_exit:
  17942.     -- 'stop', 'rebuild' never get here, this is only for 'start_full', 'start_incr'
  17943.     -- here we commit the changes for all tables on which the operation succeeded.  
  17944.     -- Before 'goto error_exit' is called, schema changes made to table currently 
  17945.     -- under cursor must be undone (so far, no schema changes)
  17946.     commit tran
  17947.     return 1    -- sp_fulltext_catalog
  17948.  
  17949. go
  17950.  
  17951. ----------------------------- sp_fulltext_table -------------------------------
  17952.  
  17953. raiserror(15339,-1,-1,'sp_fulltext_table')
  17954. go
  17955. create proc sp_fulltext_table
  17956.     @tabname    nvarchar(517),
  17957.     @action        varchar(50),
  17958.     @ftcat        sysname = NULL,        -- create: catalog name
  17959.     @keyname    sysname = NULL        -- create: name of unique index
  17960. as
  17961.     declare @schemamodified int
  17962.     -- FULLTEXT MUST BE ACTIVE IN DATABASE --
  17963.     if DatabaseProperty(db_name(), 'IsFulltextEnabled') = 0
  17964.     begin
  17965.         raiserror(15601,-1,-1)
  17966.         return 1
  17967.     end
  17968.  
  17969.     -- VALIDATE PARAMS --
  17970.     if @action is null
  17971.         OR @action not in ('create','drop','activate','deactivate',
  17972.             'start_change_tracking', 'stop_change_tracking',
  17973.             'start_background_updateindex', 'stop_background_updateindex',
  17974.             'update_index', 'start_full', 'start_incremental', 'stop')
  17975.         OR (@action not in ('create') and (@ftcat is not null or @keyname is not null))
  17976.         OR (@action in ('create') and (@ftcat is null or @keyname is null))
  17977.     begin
  17978.         raiserror(15600,-1,-1,'sp_fulltext_table')
  17979.         return 1
  17980.     end
  17981.  
  17982.     -- DISALLOW USER TRANSACTION --
  17983.     set implicit_transactions off
  17984.     if @@trancount > 0
  17985.     begin
  17986.         raiserror(15002,-1,-1,'sp_fulltext_table')
  17987.         return 1
  17988.     end
  17989.  
  17990.     -- VALIDATE TABLE NAME --
  17991.     --  (1) Must exist in current database
  17992.     declare @objid int
  17993.     select @objid = object_id(@tabname, 'local')
  17994.     if @objid is null
  17995.     begin
  17996.         declare @curdbname sysname
  17997.         select @curdbname = db_name()
  17998.         raiserror(15009,-1,-1 ,@tabname, @curdbname)
  17999.         return 1
  18000.     end
  18001.     --  (2) Must be a user table (and not a temp table)
  18002.     if ObjectProperty(@objid, 'IsUserTable') = 0 OR substring(parsename(@tabname,1),1,1) = '#'
  18003.     begin
  18004.         raiserror(15218,-1,-1 ,@tabname)
  18005.         return 1
  18006.     end
  18007.  
  18008.     -- CHECK PERMISSION ON TABLE --
  18009.     if (is_member('db_owner') = 0) AND (is_member('db_ddladmin') = 0)
  18010.         AND (is_member(user_name(ObjectProperty(@objid, 'ownerid'))) = 0)
  18011.     begin
  18012.         raiserror(15247,-1,-1)
  18013.         return 1
  18014.     end
  18015.  
  18016.     -- CHECK DATABASE MODE (must not be read-only) --
  18017.     if DATABASEPROPERTY(db_name(), 'IsReadOnly') = 1
  18018.     begin
  18019.         raiserror(15635, -1, -1, 'sp_fulltext_table')
  18020.         return 1
  18021.     end
  18022.  
  18023.     -- BEGIN TRAN AND LOCK TABLE --
  18024.     begin tran
  18025.     dbcc lockobjectschema(@tabname)
  18026.     if @@error <> 0
  18027.     begin
  18028.         goto error_abort_exit
  18029.     end
  18030.  
  18031.     -- OBTAIN CATALOG NAME FROM SYSOBJECTS & CHECK ACTION --
  18032.     declare @ftcatid smallint
  18033.     select @ftcatid = ObjectProperty(@objid, 'TableFulltextCatalogId')
  18034.     if @ftcatid <> 0 and @action = 'create'
  18035.     begin
  18036.         raiserror(15605,-1,-1,@tabname)
  18037.         goto error_abort_exit
  18038.     end
  18039.     if @ftcatid = 0 and @action <> 'create'
  18040.     begin
  18041.         raiserror(15606,-1,-1,@tabname)
  18042.         goto error_abort_exit
  18043.     end
  18044.  
  18045.     if @action = 'create'
  18046.     begin
  18047.         -- CHECK CATALOG NAME --
  18048.         select @ftcatid = null
  18049.         select @ftcatid = ftcatid from sysfulltextcatalogs where name = @ftcat
  18050.         if @ftcatid is null
  18051.         begin
  18052.             raiserror(7641,-1,-1,@ftcat)
  18053.             goto error_abort_exit
  18054.         end
  18055.  
  18056.         -- CHECK INDEX NAME (UNIQUE, SINGLE-KEY, 450-byte MAX, NON-NULLABLE) AND SET BIT IF FOUND --
  18057.         if IndexProperty(@objid, @keyname, 'IsUnique') = 1 and
  18058.            IndexProperty(@objid, @keyname, 'UserKeyCount') = 1 and
  18059.            IndexProperty(@objid, @keyname, 'IsHypothetical') = 0 and
  18060.            exists (select * from syscolumns where id = @objid and name = Index_col(@tabname, IndexProperty(@objid, @keyname, 'IndexId'), 1)
  18061.                 and length <= 450 and isnullable = 0)
  18062.         begin
  18063.             update sysindexes set status = status | 33554432 where id = @objid
  18064.                 and name = @keyname and indid > 0 and indid < 255
  18065.         end
  18066.         else
  18067.         begin
  18068.             raiserror(15607,-1,-1,@keyname)
  18069.             goto error_abort_exit
  18070.         end
  18071.  
  18072.         -- ADD CATALOG NAME TO SYSOBJECTS --
  18073.         update sysobjects set ftcatid = @ftcatid where id = @objid
  18074.  
  18075.         -- ADD TO CATALOG
  18076.         DBCC CALLFULLTEXT ( 5, @ftcatid, @objid )    -- FTAddURL( @ftcatid, db_id(), @objid )
  18077.         if @@error <> 0
  18078.             goto error_abort_exit
  18079.  
  18080.     end
  18081.  
  18082.     if @action = 'drop'
  18083.     begin
  18084.         -- DROP FROM CATALOG (NO ERROR IF ALREADY DROPPED) --
  18085.         DBCC CALLFULLTEXT ( 6, @ftcatid, @objid )    -- FTDropURL( @ftcatid, db_id(), @objid )
  18086.         if @@error <> 0
  18087.             goto error_abort_exit
  18088.  
  18089.         -- DELETE SYSDEPENDS ENTRIES FOR IMAGE COLUMNS, IF ANY --
  18090.         delete sysdepends where [id] = @objid and
  18091.                           depid = @objid and
  18092.                           deptype = 1 and
  18093.                           number in ( select colid from syscolumns where [id] = @objid and
  18094.                                                                          type = 34 and
  18095.                                                                          (colstat & 16) = 16 )
  18096.  
  18097.         -- REMOVE CATALOG NAME AND BITS FROM SYSTEM TABLES --
  18098.         update syscolumns set colstat = colstat & ~80, language = 0 where [id] = @objid
  18099.         update sysindexes set status = status & ~33554432 where [id] = @objid
  18100.         update sysobjects set status = status & ~200, ftcatid = 0 where [id] = @objid
  18101.  
  18102.         -- DELETE NOTIFICATIONS FROM SYSFULLTEXTNOTIFY --
  18103.         delete sysfulltextnotify where tableid = @objid
  18104.  
  18105.     end
  18106.  
  18107.     if @action = 'activate'
  18108.     begin
  18109.  
  18110.         -- MUST HAVE AT LEAST ONE COLUMN MARKED FOR FULLTEXT INDEXING --
  18111.         if not exists (select * from syscolumns where id = @objid and (colstat & 16) = 16)
  18112.         begin
  18113.             raiserror(15609, -1,-1,@tabname)
  18114.             goto error_abort_exit
  18115.         end
  18116.  
  18117.         -- NO ERROR IF INDEXING ALREADY ACTIVATED --
  18118.         if ObjectProperty(@objid, 'TableHasActiveFulltextIndex') = 1
  18119.         begin
  18120.             rollback tran
  18121.             return 0
  18122.         end
  18123.  
  18124.  
  18125.         update sysobjects set status = status | 8 where id = @objid
  18126.  
  18127.         if (ObjectProperty(@objid, 'TableFulltextChangeTrackingOn') = 1)
  18128.         begin
  18129.  
  18130.             -- STOP A FULL/INCREMENTAL POPULATION FOR THIS TABLE --
  18131.             DBCC CALLFULLTEXT ( 12, @ftcatid, @objid, 2 )
  18132.             if @@error <> 0
  18133.                 goto error_abort_exit
  18134.  
  18135.             -- DELETE SYSFULLTEXTNOTIFY ENTRIES
  18136.             delete sysfulltextnotify where tableid = @objid
  18137.  
  18138.             -- START A FULL CRAWL FOR THE TABLE
  18139.             DBCC CALLFULLTEXT ( 12, @ftcatid, @objid, 0 )
  18140.             if @@error <> 0
  18141.                 goto error_abort_exit
  18142.  
  18143.         end
  18144.  
  18145.  
  18146.     end
  18147.  
  18148.     if @action = 'deactivate'
  18149.     begin
  18150.         -- NO ERROR IF INDEXING ALREADY DEACTIVATED --
  18151.         if ObjectProperty(@objid, 'TableHasActiveFulltextIndex') = 0
  18152.         begin
  18153.             rollback tran
  18154.             return 0
  18155.         end
  18156.  
  18157.         -- IF TABLE IS NOT ENABLED FOR NOTIFICATIONS --
  18158.         if ObjectProperty(@objid, 'TableFulltextChangeTrackingOn') = 0
  18159.         begin
  18160.             -- SET STATE TO INACTIVE, SCHEMA-MODIFIED
  18161.             update sysobjects set status = ((status & ~72) | 128) where id = @objid
  18162.         end
  18163.         else
  18164.         begin
  18165.             -- SET STATE TO INACTIVE
  18166.             update sysobjects set status = (status & ~8) where id = @objid
  18167.         end
  18168.  
  18169.         -- DELETE SYSFULLTEXTNOTIFY ENTRIES
  18170.         delete sysfulltextnotify where tableid = @objid
  18171.  
  18172.         -- STOP EXISTING CRAWL (IMPLICIT STOP WITH WARNING)
  18173.         DBCC CALLFULLTEXT ( 12, @ftcatid, @objid, 2 )
  18174.         if @@error <> 0
  18175.             goto error_abort_exit
  18176.  
  18177.  
  18178.     end
  18179.  
  18180.     if @action = 'start_change_tracking'
  18181.     begin
  18182.         -- ERROR IF TABLE IS NOT ACTIVATED --
  18183.         if (ObjectProperty(@objid, 'TableHasActiveFulltextIndex') = 0)
  18184.         begin
  18185.             raiserror(15630,-1,-1, @tabname)
  18186.             goto error_abort_exit
  18187.         end
  18188.  
  18189.         -- ERROR IF TABLE IS ALREADY ENABLED FOR NOTIFICATIONS --
  18190.         if ObjectProperty(@objid, 'TableFulltextChangeTrackingOn') = 1
  18191.         begin
  18192.             raiserror(15631,-1,-1, @tabname)
  18193.             goto error_abort_exit
  18194.         end
  18195.  
  18196.         -- ERROR IF DATABASE IS IN SINGLE USER MODE --
  18197.         if DATABASEPROPERTY(db_name(), 'IsSingleUser') = 1
  18198.         begin
  18199.             raiserror(15637, -1, -1, @tabname)
  18200.             goto error_abort_exit
  18201.         end
  18202.  
  18203.         -- CHECK TO SEE IF THERE ARE ANY COLUMNS WHICH ARE NOT IN ROW BLOBS --
  18204.         if (select count(*) from syscolumns where
  18205.             (id = object_id(@tabname)) and ((xtype = 34) or (xtype = 35) or (xtype = 99)) and
  18206.             ((colstat & 16) != 0) and (length = 16)) > 0
  18207.         begin
  18208.             raiserror(15639, -1, -1, @tabname)
  18209.         end
  18210.  
  18211.         -- STOP EXISTING CRAWL
  18212.         DBCC CALLFULLTEXT ( 12, @ftcatid, @objid, 2 )
  18213.         if @@error <> 0
  18214.             goto error_abort_exit
  18215.  
  18216.         -- DELETE SYSFULLTEXTNOTIFY ENTRIES
  18217.         delete sysfulltextnotify where tableid = @objid
  18218.  
  18219.         select @schemamodified = ObjectProperty(@objid, 'TableIsFulltextSchemaModified')
  18220.  
  18221.         -- SET TABLE TO CT ON. SCHEMA MOD. OFF --
  18222.         update sysobjects set status = ((status & ~128) | 64) where id = @objid
  18223.  
  18224.         -- COMMIT TRAN -- NESCESSARY TO TURN ON CT BEFORE CRAWL IS KICKED OFF --
  18225.         commit tran
  18226.         if @@error <> 0
  18227.             goto error_abort_exit
  18228.  
  18229.         if (@schemamodified = 1)
  18230.         begin
  18231.             -- START A FULL POPULATION FOR THIS TABLE --
  18232.             DBCC CALLFULLTEXT ( 12, @ftcatid, @objid, 0 )
  18233.             if @@error <> 0
  18234.             begin
  18235.                 -- NEED TO RUN A FULL POPULATION
  18236.                 raiserror(15644, -1, -1,@tabname, 'start_full')
  18237.                 return 1
  18238.             end
  18239.         end
  18240.         else
  18241.         begin
  18242.             -- START AN INCREMENTAL POPULATION FOR THIS TABLE --
  18243.             DBCC CALLFULLTEXT ( 12, @ftcatid, @objid, 1 )
  18244.             if @@error <> 0
  18245.             begin
  18246.                 -- NEED TO RUN AN INCREMENTAL POPULATION
  18247.                 raiserror(15644, -1, -1, @tabname, 'start_incremental')
  18248.                 return 1
  18249.             end
  18250.         end
  18251.         return 0
  18252.  
  18253.     end
  18254.  
  18255.     if @action = 'stop_change_tracking'
  18256.     begin
  18257.         -- ERROR IF TABLE IS NOT ACTIVATED --
  18258.         if (ObjectProperty(@objid, 'TableHasActiveFulltextIndex') = 0)
  18259.         begin
  18260.             raiserror(15630,-1,-1, @tabname)
  18261.             goto error_abort_exit
  18262.         end
  18263.  
  18264.         if (ObjectProperty(@objid, 'TableFulltextChangeTrackingOn') = 0)
  18265.         begin
  18266.             rollback tran
  18267.                 return 0
  18268.         end
  18269.  
  18270.         if(ObjectProperty(@objid, 'TableFulltextPopulateStatus') != 0)
  18271.         begin
  18272.             raiserror(7640,-1,-1, @tabname)    
  18273.         end
  18274.  
  18275.         -- DISABLE FULLTEXT AUTO PROPAGATION (NO ERROR IF ALREADY DISABLED) --
  18276.         DBCC CALLFULLTEXT ( 9, @objid )    -- FTDisableNotify( db_id(), @objid )
  18277.         if @@error <> 0
  18278.             goto error_abort_exit
  18279.  
  18280.         -- TURN OFF ACTIVE BITS IN SYSOBJECTS --
  18281.         update sysobjects set status = status & ~192 where id = @objid
  18282.  
  18283.         if ((select count(*) from sysfulltextnotify where tableid = @objid) != 0)
  18284.         begin
  18285.             raiserror(7638,-1,-1, @tabname)
  18286.         end
  18287.  
  18288.         -- DELETE NOTIFICATIONS FROM SYSFULLTEXTNOTIFY --
  18289.         delete sysfulltextnotify where tableid = @objid
  18290.  
  18291.  
  18292.     end
  18293.  
  18294.     if @action = 'start_background_updateindex'
  18295.     begin
  18296.         -- ERROR IF TABLE IS NOT ACTIVATED --
  18297.         if ObjectProperty(@objid, 'TableHasActiveFulltextIndex') = 0
  18298.         begin
  18299.             raiserror(15630,-1,-1, @tabname)
  18300.             goto error_abort_exit
  18301.         end
  18302.  
  18303.  
  18304.         -- ERROR IF TABLE IS NOT ENABLED FOR NOTIFICATIONS --
  18305.         if ObjectProperty(@objid, 'TableFulltextChangeTrackingOn') = 0
  18306.         begin
  18307.             raiserror(15632,-1,-1, @tabname)
  18308.             goto error_abort_exit
  18309.         end
  18310.  
  18311.         -- ERROR IF FULLTEXT SCHEMA OF THE TABLE HAS BEEN MODIFIED (SHOULD NEVER HAPPEN)--
  18312.         if (ObjectProperty(@objid, 'TableIsFulltextSchemaModified') = 1)
  18313.         begin
  18314.             raiserror(15640,-1,-1, @tabname)
  18315.             goto error_abort_exit
  18316.         end
  18317.  
  18318.         -- ERROR IF TABLE IS ALREADY ENABLED FOR AUTO PROPAGATION --
  18319.         if ObjectProperty(@objid, 'TableFulltextBackgroundUpdateIndexOn') = 1
  18320.         begin
  18321.             raiserror(15633,-1,-1, @tabname)
  18322.             goto error_abort_exit
  18323.         end
  18324.  
  18325.         -- ENABLE TABLE FOR FULLTEXT AUTO PROPAGATION --
  18326.         DBCC CALLFULLTEXT ( 10, @ftcatid, @objid ) -- FTEnableAutoProp( @ftcatid, db_id(), @objid )
  18327.         if @@error <> 0
  18328.             goto error_abort_exit
  18329.  
  18330.         -- TURN ON FULLTEXT AUTOPROPAGATION BIT IN SYSOBJECTS --
  18331.         update sysobjects set status = status | 128 where id = @objid
  18332.     end
  18333.  
  18334.     if @action = 'stop_background_updateindex'
  18335.     begin
  18336.         -- ERROR IF TABLE IS NOT ACTIVATED --
  18337.         if (ObjectProperty(@objid, 'TableHasActiveFulltextIndex') = 0)
  18338.         begin
  18339.             raiserror(15630,-1,-1, @tabname)
  18340.             goto error_abort_exit
  18341.         end
  18342.  
  18343.         if (ObjectProperty(@objid, 'TableFullTextBackgroundUpdateIndexOn') = 0)
  18344.         begin
  18345.             rollback tran
  18346.             return 0
  18347.         end
  18348.  
  18349.         -- DISABLE FULLTEXT AUTO PROPAGATION (NO ERROR IF ALREADY DISABLED) --
  18350.         DBCC CALLFULLTEXT ( 9, @objid )    -- FTDisableNotify( db_id(), @objid )
  18351.         if @@error <> 0
  18352.             goto error_abort_exit
  18353.  
  18354.         -- TURN OFF ACTIVE BITS IN SYSOBJECTS --
  18355.         update sysobjects set status = status & ~128 where id = @objid
  18356.     end
  18357.  
  18358.     if @action = 'update_index'
  18359.     begin
  18360.  
  18361.         -- ERROR IF TABLE IS NOT ENABLED FOR NOTIFICATIONS --
  18362.         if ObjectProperty(@objid, 'TableFulltextChangeTrackingOn') = 0
  18363.         begin
  18364.             raiserror(15634,-1,-1, @tabname)
  18365.             goto error_abort_exit
  18366.         end
  18367.  
  18368.         -- ERROR IF TABLE IS NOT ACTIVE ANY MORE --
  18369.         if (ObjectProperty(@objid, 'TableHasActiveFulltextIndex') = 0)
  18370.         begin
  18371.             raiserror(15630,-1,-1, @tabname)
  18372.             goto error_abort_exit
  18373.         end
  18374.  
  18375.         -- ERROR IF FULLTEXT SCHEMA OF THE TABLE HAS BEEN MODIFIED -- THIS SHOULD NEVER HAPPEN
  18376.         if (ObjectProperty(@objid, 'TableIsFulltextSchemaModified') = 1)
  18377.         begin
  18378.             raiserror(15640,-1,-1, @tabname)
  18379.             goto error_abort_exit
  18380.         end
  18381.  
  18382.         -- ERROR IF DATABASE IS IN SIGNLE USER MODE --
  18383.         if DATABASEPROPERTY(db_name(), 'IsSingleUser') = 1
  18384.         begin
  18385.             raiserror(15637, -1, -1, @tabname)
  18386.             goto error_abort_exit
  18387.         end
  18388.  
  18389.         DBCC CALLFULLTEXT ( 11, @ftcatid, @objid )    -- FTStartPropagation( db_id(), @ftcatid, @objid )
  18390.         if @@error <> 0
  18391.             goto error_abort_exit
  18392.     end
  18393.  
  18394.     if @action = 'start_full'
  18395.     begin
  18396.         -- ERROR IF TABLE IS NOT ACTIVATED --
  18397.         if ObjectProperty(@objid, 'TableHasActiveFulltextIndex') = 0
  18398.         begin
  18399.             raiserror(15630,-1,-1, @tabname)
  18400.             goto error_abort_exit
  18401.         end
  18402.  
  18403.         -- ERROR IF DATABASE IS IN SINGLE USER MODE --
  18404.         if DATABASEPROPERTY(db_name(), 'IsSingleUser') = 1
  18405.         begin
  18406.             raiserror(15637, -1, -1, @tabname)
  18407.             goto error_abort_exit
  18408.         end
  18409.  
  18410.         -- RAISE WARNING IF POPULATE STATUS OF THE TABLE IS NOT IDLE
  18411.         if (ObjectProperty(@objid, 'TableFulltextPopulateStatus') != 0)
  18412.         begin
  18413.             raiserror(7636,-1,-1, @tabname)
  18414.             goto error_abort_exit
  18415.         end
  18416.  
  18417.         -- DELETE SYSFULLTEXTNOTIFY ENTRIES
  18418.         delete sysfulltextnotify where tableid = @objid
  18419.  
  18420.         -- START A FULL POPULATION FOR THIS TABLE --
  18421.         DBCC CALLFULLTEXT ( 12, @ftcatid, @objid, 0 )
  18422.         if @@error <> 0
  18423.             goto error_abort_exit
  18424.  
  18425.         if (ObjectProperty(@objid, 'TableIsFulltextSchemaModified') = 1)
  18426.         and (ObjectProperty(@objid, 'TableFulltextChangeTrackingOn') = 0)
  18427.             -- SET TABLE SCHEMA-UNMODIFIED
  18428.             update sysobjects set status = status & ~128 where id = @objid
  18429.  
  18430.     end
  18431.  
  18432.     if @action = 'start_incremental'
  18433.     begin
  18434.         -- ERROR IF TABLE IS NOT ACTIVATED --
  18435.         if ObjectProperty(@objid, 'TableHasActiveFulltextIndex') = 0
  18436.         begin
  18437.             raiserror(15630,-1,-1, @tabname)
  18438.             goto error_abort_exit
  18439.         end
  18440.  
  18441.         -- ERROR IF DATABASE IS IN SINGLE USER MODE --
  18442.         if DATABASEPROPERTY(db_name(), 'IsSingleUser') = 1
  18443.         begin
  18444.             raiserror(15637, -1, -1, @tabname)
  18445.             goto error_abort_exit
  18446.         end
  18447.  
  18448.         -- RAISE WARNING IF POPULATE STATUS OF THE TABLE IS NOT IDLE
  18449.         if (ObjectProperty(@objid, 'TableFulltextPopulateStatus') != 0)
  18450.         begin
  18451.             raiserror(7636,-1,-1, @tabname)
  18452.             goto error_abort_exit
  18453.         end
  18454.  
  18455.         -- DELETE SYSFULLTEXTNOTIFY ENTRIES
  18456.         delete sysfulltextnotify where tableid = @objid
  18457.  
  18458.         -- START AN INCREMENTAL POPULATION FOR THIS TABLE --
  18459.         if (ObjectProperty(@objid, 'TableIsFulltextSchemaModified') = 1)
  18460.             and (ObjectProperty(@objid, 'TableFulltextChangeTrackingOn') = 0)
  18461.             begin
  18462.             -- FULL CRAWL IF SCHEMA MODIFIED
  18463.             DBCC CALLFULLTEXT ( 12, @ftcatid, @objid, 0 )
  18464.             if @@error <> 0
  18465.                 goto error_abort_exit
  18466.  
  18467.             -- SET TABLE SCHEMA-UNMODIFIED
  18468.             update sysobjects set status = status & ~128 where id = @objid
  18469.         end
  18470.         else
  18471.         begin
  18472.             -- INCREMENTAL CRAWL
  18473.             DBCC CALLFULLTEXT ( 12, @ftcatid, @objid, 1 )
  18474.             if @@error <> 0
  18475.                 goto error_abort_exit
  18476.         end
  18477.     end
  18478.  
  18479.     if @action = 'stop'
  18480.     begin
  18481.         -- ERROR IF TABLE IS NOT ACTIVATED --
  18482.         if ObjectProperty(@objid, 'TableHasActiveFulltextIndex') = 0
  18483.         begin
  18484.             raiserror(15630,-1,-1, @tabname)
  18485.             goto error_abort_exit
  18486.         end
  18487.  
  18488.         -- ERROR IF POPULATE STATUS OF THE TABLE IS CRAWLING AND CT ON
  18489.         if (ObjectProperty(@objid, 'TableFulltextChangeTrackingOn') = 1)
  18490.         and ((ObjectProperty(@objid, 'TableFulltextPopulateStatus') = 1)
  18491.         or (ObjectProperty(@objid, 'TableFulltextPopulateStatus') = 2))
  18492.         begin
  18493.             raiserror(15642,-1,-1, @tabname)
  18494.             goto error_abort_exit
  18495.         end
  18496.  
  18497.         -- STOP A FULL/INCREMENTAL POPULATION FOR THIS TABLE --
  18498.         DBCC CALLFULLTEXT ( 12, @ftcatid, @objid, 2 )
  18499.         if @@error <> 0
  18500.             goto error_abort_exit
  18501.     end
  18502.  
  18503.     -- COMMIT TRAN --
  18504.     commit tran
  18505.     if @@error <> 0
  18506.         goto error_abort_exit
  18507.  
  18508.     -- SUCCESS --
  18509.     return 0
  18510.  
  18511. error_abort_exit:
  18512.     rollback tran
  18513.     return 1    -- sp_fulltext_table
  18514. go
  18515.  
  18516. ---------------------------- sp_fulltext_column -------------------------------
  18517.  
  18518. raiserror(15339,-1,-1,'sp_fulltext_column')
  18519. go
  18520. create proc sp_fulltext_column
  18521.     @tabname        nvarchar(517),      -- table name
  18522.     @colname        sysname,            -- column name
  18523.     @action         varchar(20),        -- add | drop
  18524.     @language       int = null,         -- LCID of data in the column
  18525.     @type_colname   sysname = null      -- column name, valid if colname is img
  18526.  
  18527. as
  18528.     -- FULLTEXT MUST BE ACTIVE IN DATABASE --
  18529.     if DatabaseProperty(db_name(), 'IsFulltextEnabled') = 0
  18530.     begin
  18531.         raiserror(15601,-1,-1)
  18532.         return 1
  18533.     end
  18534.  
  18535.     -- VALIDATE PARAMS --
  18536.     if @action is null or @action not in ('add','drop')
  18537.     begin
  18538.         raiserror(15600,-1,-1,'sp_fulltext_column')
  18539.         return 1
  18540.     end
  18541.  
  18542.     -- DISALLOW USER TRANSACTION --
  18543.     set implicit_transactions off
  18544.     if @@trancount > 0
  18545.     begin
  18546.         raiserror(15002,-1,-1,'sp_fulltext_column')
  18547.         return 1
  18548.     end
  18549.  
  18550.     -- VALIDATE TABLE NAME --
  18551.     --    (1) Must exist in current database
  18552.     declare @objid int
  18553.     select @objid = object_id(@tabname, 'local')
  18554.     if @objid is null
  18555.     begin
  18556.         declare @curdbname sysname
  18557.         select @curdbname = db_name()
  18558.         raiserror(15009,-1,-1 ,@tabname, @curdbname)
  18559.         return 1
  18560.     end
  18561.     --    (2) Must be a user table
  18562.     if ObjectProperty(@objid, 'IsUserTable') = 0
  18563.     begin
  18564.         raiserror(15218,-1,-1 ,@tabname)
  18565.         return 1
  18566.     end
  18567.  
  18568.     -- CHECK PERMISSION ON TABLE --
  18569.     if (is_member('db_owner') = 0) AND (is_member('db_ddladmin') = 0)
  18570.         AND (is_member(user_name(ObjectProperty(@objid, 'ownerid'))) = 0)
  18571.     begin
  18572.         raiserror(15247,-1,-1)
  18573.         return 1
  18574.     end
  18575.  
  18576.     -- CHECK DATABASE MODE (must not be read-only) --
  18577.     if DATABASEPROPERTY(db_name(), 'IsReadOnly') = 1
  18578.     begin
  18579.         raiserror(15635, -1, -1, 'sp_fulltext_column')
  18580.         return 1
  18581.     end
  18582.  
  18583.     -- BEGIN TRAN AND LOCK TABLE --
  18584.     begin tran
  18585.     dbcc lockobjectschema(@tabname)
  18586.     if @@error <> 0
  18587.     begin
  18588.         goto error_abort_exit
  18589.     end
  18590.  
  18591.     -- CHECK FOR CATALOG IN SYSOBJECTS --
  18592.     declare @ftcatid smallint
  18593.     select @ftcatid = ObjectProperty(@objid, 'TableFulltextCatalogId')
  18594.  
  18595.     if @ftcatid = 0
  18596.     begin
  18597.         raiserror(15606,-1,-1,@tabname)
  18598.         goto error_abort_exit
  18599.     end
  18600.  
  18601.     -- VALIDATE COLUMN NAME (CANNOT BE COMPUTED) --
  18602.     declare @typename sysname
  18603.     select @typename = type_name(ColumnProperty(@objid, @colname, 'SystemType'))
  18604.     if @typename is null OR ColumnProperty(@objid, @colname, 'IsComputed') = 1
  18605.     begin
  18606.         raiserror(15104,-1,-1,@tabname,@colname)
  18607.         goto error_abort_exit
  18608.     end
  18609.  
  18610.     -- VALIDATE PARAMETERS
  18611.     if (@action <> 'add' or @typename <> N'image') and @type_colname is not null
  18612.     begin
  18613.         raiserror(15600, -1, -1, 'sp_fulltext_column')
  18614.         goto error_abort_exit
  18615.     end
  18616.  
  18617.     if @action = 'add'
  18618.     begin
  18619.         -- VALIDATE COLUMN TYPE --
  18620.         if @typename not in (N'nchar',N'nvarchar',N'ntext',N'char',N'varchar',N'text', N'image')
  18621.         begin
  18622.             raiserror(15611,-1,-1,@colname,@tabname)
  18623.             goto error_abort_exit
  18624.         end
  18625.  
  18626.         -- LANGUAGE
  18627.         if @language is null
  18628.             begin
  18629.                 -- USE THE SERVER DEFAULT WORD BREAKING LANGUAGE
  18630.                 select @language = value from master.dbo.syscurconfigs where config = 1126
  18631.             end
  18632.         else
  18633.             begin
  18634.                 -- VALIDATE @LANGUAGE ARGUMENT
  18635.                 if @language < 0
  18636.                 begin
  18637.                     raiserror(15600,-1,-1,'sp_fulltext_column')
  18638.                     goto error_abort_exit
  18639.                 end
  18640.             end
  18641.  
  18642.         update syscolumns set language = @language where id = @objid and name = @colname
  18643.  
  18644.         -- IF TABLE HAS ZERO INDEXED COLUMNS (THIS IS THE FIRST COLUMN TO BE ADDED), MARK IT ACTIVE
  18645.         if not exists (select * from syscolumns where id = @objid and (colstat & 16) = 16)
  18646.             and (ObjectProperty(@objid, 'TableFulltextChangeTrackingOn') = 0)
  18647.             and (ObjectProperty(@objid, 'TableIsFulltextSchemaModified') = 0)
  18648.         begin
  18649.             update sysobjects set status = (status  | 8) where id = @objid
  18650.         end
  18651.  
  18652.         -- SET THE BIT FOR THIS COLUMN --
  18653.         update syscolumns set colstat = colstat | 16 where id = @objid and name = @colname
  18654.  
  18655.         -- STOP A FULL/INCREMENTAL POPULATION FOR THIS TABLE --
  18656.         DBCC CALLFULLTEXT ( 12, @ftcatid, @objid, 2 )
  18657.         if @@error <> 0
  18658.             goto error_abort_exit
  18659.  
  18660.         if ObjectProperty(@objid, 'TableFulltextChangeTrackingOn') = 1
  18661.         begin
  18662.  
  18663.  
  18664.             if ObjectProperty(@objid, 'TableHasActiveFulltextIndex') = 1
  18665.             begin
  18666.  
  18667.                 -- DELETE SYSFULLTEXTNOTIFY ENTRIES
  18668.                 delete sysfulltextnotify where tableid = @objid
  18669.  
  18670.                 -- START A FULL CRAWL FOR THE TABLE
  18671.                 DBCC CALLFULLTEXT ( 12, @ftcatid, @objid, 0 )
  18672.                 if @@error <> 0
  18673.                     goto error_abort_exit
  18674.             end
  18675.  
  18676.         end
  18677.         else
  18678.         begin
  18679.  
  18680.             -- SET STATE TO SCHEMA_MODIFIED
  18681.             update sysobjects set status = ((status & ~64) | 128) where id = @objid
  18682.         end
  18683.  
  18684.         if @typename = N'image'
  18685.         begin
  18686.             -- VALIDATE THAT THE TYPE COLUMN IS GIVEN AND THAT IT IS VALID
  18687.             if @type_colname is null
  18688.             begin
  18689.                 raiserror(15600, -1, -1, 'sp_fulltext_column')
  18690.                 goto error_abort_exit
  18691.             end
  18692.  
  18693.             declare @typecolname sysname
  18694.             select @typecolname = type_name(ColumnProperty(@objid, @type_colname, 'SystemType'))
  18695.  
  18696.             -- TYPE COLUMN HAS TO BE A CHARACTER COLUMN
  18697.             if @typecolname not in (N'nchar',N'nvarchar',N'char',N'varchar')
  18698.             begin
  18699.                 raiserror(15600 , -1, -1, 'sp_fulltext_column')
  18700.                 goto error_abort_exit
  18701.             end
  18702.  
  18703.             -- ADD ENTRY OF COLID IN SYSDEPENDS
  18704.             declare @colid smallint
  18705.             declare @type_colid smallint
  18706.  
  18707.             select @colid = colid from syscolumns where [id] = @objid and name = @colname
  18708.             select @type_colid = colid from syscolumns where [id]  = @objid and name = @type_colname
  18709.  
  18710.             if not exists ( select [id] from sysdepends
  18711.                             where  [id] = @objid and
  18712.                                    depid = @objid and
  18713.                                    number = @colid )
  18714.             begin
  18715.                 insert into sysdepends ([id], depid, number, depnumber, status, deptype )
  18716.                         values( @objid, @objid, @colid, @type_colid, 0, 1)
  18717.             end
  18718.  
  18719.             -- SET BIT INDICATING TYPE COLUMN
  18720.             update syscolumns set colstat = colstat | 64 where id = @objid and name = @type_colname
  18721.         end
  18722.  
  18723.     end
  18724.     else
  18725.     begin
  18726.         -- CLEAR THE BIT & ZERO LCID FOR THIS COLUMN --
  18727.         update syscolumns set colstat = colstat & ~16, language = 0
  18728.             where id = @objid and name = @colname
  18729.  
  18730.         -- IF LAST COLUMN DROPPED
  18731.         if not exists (select * from syscolumns where id = @objid and (colstat & 16) = 16)
  18732.         begin
  18733.             -- STOP A FULL/INCREMENTAL POPULATION FOR THIS TABLE --
  18734.             DBCC CALLFULLTEXT ( 12, @ftcatid, @objid, 2 )
  18735.             if @@error <> 0
  18736.                 goto error_abort_exit
  18737.  
  18738.             -- IF TABLE HAS NOT BEEN DEACTIVATED
  18739.             if ((ObjectProperty(@objid, 'TableHasActiveFulltextIndex') = 1)
  18740.                 or (ObjectProperty(@objid, 'TableIsFulltextSchemaModified') = 0))
  18741.             begin
  18742.  
  18743.                 -- IF CHANGE-TRACKING IS OFF
  18744.                 if ObjectProperty(@objid, 'TableFulltextChangeTrackingOn') = 0
  18745.                 begin
  18746.                     -- SET TABLE TO SCHEMA UNMODIFIED, INACTIVE (TURN OFF ALL BITS)
  18747.                     update sysobjects set status = (status & ~200) where id = @objid
  18748.                 end
  18749.                 else
  18750.                 begin
  18751.                     -- SET TABLE TO INACTIVE
  18752.                     update sysobjects set status = (status & ~8) where id = @objid
  18753.                 end
  18754.             end
  18755.         end
  18756.         else
  18757.         if ObjectProperty(@objid, 'TableFulltextChangeTrackingOn') = 1
  18758.         begin
  18759.  
  18760.             -- STOP A FULL/INCREMENTAL POPULATION FOR THIS TABLE --
  18761.             DBCC CALLFULLTEXT ( 12, @ftcatid, @objid, 2 )
  18762.             if @@error <> 0
  18763.                 goto error_abort_exit
  18764.  
  18765.             if ObjectProperty(@objid, 'TableHasActiveFulltextIndex') = 1
  18766.             begin
  18767.                 -- DELETE SYSFULLTEXTNOTIFY ENTRIES
  18768.                 delete sysfulltextnotify where tableid = @objid
  18769.  
  18770.                 -- START A FULL CRAWL FOR THE TABLE
  18771.                 DBCC CALLFULLTEXT ( 12, @ftcatid, @objid, 0 )
  18772.                 if @@error <> 0
  18773.                     goto error_abort_exit
  18774.             end
  18775.  
  18776.         end
  18777.         else
  18778.         begin
  18779.  
  18780.             -- STOP A FULL/INCREMENTAL POPULATION FOR THIS TABLE --
  18781.             DBCC CALLFULLTEXT ( 12, @ftcatid, @objid, 2 )
  18782.             if @@error <> 0
  18783.                 goto error_abort_exit
  18784.  
  18785.             -- SET BITS IN SYSOBJECTS
  18786.             update sysobjects set status = ((status & ~64) | 128) where id = @objid
  18787.         end
  18788.  
  18789.         -- IF IMAGE COLUMN, UNBIND FROM THE TYPE COLUMN
  18790.         if @typename = N'image'
  18791.         begin
  18792.             declare @colid1 smallint
  18793.             declare @type_colid1 smallint
  18794.  
  18795.             select @colid1 = colid from syscolumns where [id] = @objid and name = @colname
  18796.             select @type_colid1 = depnumber from sysdepends
  18797.                     where [id] = @objid and
  18798.                          depid = @objid and
  18799.                          number = @colid1
  18800.  
  18801.             delete sysdepends where [id] = @objid and
  18802.                                     depid = @objid and
  18803.                                     number = @colid1 and
  18804.                                     depnumber = @type_colid1 and
  18805.                                     deptype = 1
  18806.  
  18807.             -- CLEAR BIT RELATING THE IMAGE COLUMN AND TYPE COLUMN
  18808.             if not exists ( select depnumber from sysdepends 
  18809.                             where    [id] = @objid and
  18810.                                     depnumber = @type_colid1 and
  18811.                                     deptype = 1 and
  18812.                                     number in (select colid from syscolumns 
  18813.                                              where    [id] = @objid and
  18814.                                                     type = 34 and
  18815.                                                     (colstat & 16) = 16) )
  18816.             begin
  18817.                 update syscolumns set colstat = colstat & ~64 where [id] = @objid and colid = @type_colid1
  18818.             end
  18819.         end
  18820.  
  18821.     end
  18822.  
  18823.     -- COMMIT TRAN --
  18824.     commit tran
  18825.     if @@error <> 0
  18826.         goto error_abort_exit
  18827.  
  18828.     -- SUCCESS --
  18829.     return 0
  18830.  
  18831. error_abort_exit:
  18832.     rollback tran
  18833.     return 1    -- sp_fulltext_column
  18834. go
  18835.  
  18836. ---------------------------- sp_help_fulltext_catalogs ------------------------------
  18837.  
  18838. raiserror(15339,-1,-1,'sp_help_fulltext_catalogs')
  18839. go
  18840. create proc sp_help_fulltext_catalogs
  18841.     @fulltext_catalog_name        sysname = NULL        -- full-text catalog name
  18842. as
  18843.     -- FULLTEXT MUST BE ACTIVE IN DATABASE --
  18844.     if DatabaseProperty(db_name(), 'IsFulltextEnabled') = 0
  18845.     begin
  18846.         raiserror(15601,-1,-1)
  18847.         return 1
  18848.     end
  18849.  
  18850.     -- CATALOG MUST EXIST IF SPECIFIED --
  18851.     if @fulltext_catalog_name is not null
  18852.     begin
  18853.         declare @ftcatid smallint
  18854.         select @ftcatid = ftcatid from sysfulltextcatalogs where name = @fulltext_catalog_name
  18855.         if @ftcatid is null
  18856.         begin
  18857.             raiserror(7641,-1,-1,@fulltext_catalog_name)
  18858.             return 1
  18859.         end
  18860.     end
  18861.  
  18862.     -- RETRIEVE THE DEFAULT PATH --
  18863.     DECLARE @def_path as nvarchar(260)
  18864.     select @def_path = null
  18865.     exec master.dbo.xp_instance_regread 'HKEY_LOCAL_MACHINE',
  18866.         'SOFTWARE\Microsoft\MSSQLServer\MSSQLServer','FullTextDefaultPath',
  18867.         @def_path OUT
  18868.  
  18869.     -- SELECT ANY ROWS THAT MEET THE CRITERIA --
  18870.     select CAT.ftcatid,
  18871.        name as NAME,
  18872.            'PATH'= CASE WHEN path is NULL THEN @def_path
  18873.                         ELSE path
  18874.                         END,
  18875.            FullTextCatalogProperty(CAT.name, 'PopulateStatus') AS STATUS ,
  18876.            (select COUNT(*)
  18877.               from sysobjects
  18878.               where type='U' and sysobjects.ftcatid = CAT.ftcatid
  18879.            ) as NUMBER_FULLTEXT_TABLES
  18880.     from sysfulltextcatalogs as CAT
  18881.     where ( @fulltext_catalog_name is null or name = @fulltext_catalog_name )
  18882.     order by ftcatid
  18883.  
  18884.     -- SUCCESS --
  18885.     return 0    -- sp_help_fulltext_catalogs
  18886. go
  18887.  
  18888. ---------------------------- sp_help_fulltext_catalogs_cursor ------------------------------
  18889.  
  18890. raiserror(15339,-1,-1,'sp_help_fulltext_catalogs_cursor')
  18891. go
  18892. create proc sp_help_fulltext_catalogs_cursor
  18893.     @cursor_return CURSOR VARYING OUTPUT,
  18894.     @fulltext_catalog_name        sysname = NULL        -- full-text catalog name
  18895. as
  18896.     -- FULLTEXT MUST BE ACTIVE IN DATABASE --
  18897.     if DatabaseProperty(db_name(), 'IsFulltextEnabled') = 0
  18898.     begin
  18899.         raiserror(15601,-1,-1)
  18900.         return 1
  18901.     end
  18902.  
  18903.     -- CATALOG MUST EXIST IF SPECIFIED --
  18904.     if @fulltext_catalog_name is not null
  18905.     begin
  18906.         declare @ftcatid smallint
  18907.         select @ftcatid = ftcatid from sysfulltextcatalogs where name = @fulltext_catalog_name
  18908.         if @ftcatid is null
  18909.         begin
  18910.             raiserror(7641,-1,-1,@fulltext_catalog_name)
  18911.             return 1
  18912.         end
  18913.     end
  18914.  
  18915.     -- RETRIEVE THE DEFAULT PATH --
  18916.     DECLARE @def_path as nvarchar(260)
  18917.     select @def_path = null
  18918.     exec master.dbo.xp_instance_regread 'HKEY_LOCAL_MACHINE',
  18919.         'SOFTWARE\Microsoft\MSSQLServer\MSSQLServer','FullTextDefaultPath',
  18920.         @def_path OUT
  18921.  
  18922.     -- SELECT ANY ROWS THAT MEET THE CRITERIA --
  18923.     set @cursor_return =    CURSOR LOCAL SCROLL DYNAMIC FOR
  18924.     select CAT.ftcatid,
  18925.        name as NAME,
  18926.        'PATH'= CASE WHEN path is NULL THEN @def_path
  18927.                             ELSE path
  18928.                             END,
  18929.         FullTextCatalogProperty(CAT.name, 'PopulateStatus') AS STATUS ,
  18930.         (select COUNT(*)
  18931.          from sysobjects
  18932.          where type='U' and sysobjects.ftcatid = CAT.ftcatid
  18933.          ) as NUMBER_FULLTEXT_TABLES
  18934.         from sysfulltextcatalogs as CAT
  18935.         where ( @fulltext_catalog_name is null or name = @fulltext_catalog_name )
  18936.         order by ftcatid
  18937.  
  18938.     open @cursor_return
  18939.  
  18940.     -- SUCCESS --
  18941.     return 0    -- sp_help_fulltext_catalogs_cursor
  18942. go
  18943.  
  18944. ---------------------------- sp_help_fulltext_tables ------------------------------
  18945.  
  18946. raiserror(15339,-1,-1,'sp_help_fulltext_tables')
  18947. go
  18948. create proc sp_help_fulltext_tables
  18949.     @fulltext_catalog_name        sysname = NULL,         -- full-text catalog name
  18950.     @table_name nvarchar(517) = NULL    -- table name
  18951. as
  18952.     -- FULLTEXT MUST BE ACTIVE IN DATABASE --
  18953.     if DatabaseProperty(db_name(), 'IsFulltextEnabled') = 0
  18954.     begin
  18955.         raiserror(15601,-1,-1)
  18956.         return 1
  18957.     end
  18958.  
  18959.     -- CATALOG MUST EXIST IF SPECIFIED --
  18960.     declare @ftcatid smallint
  18961.     if @fulltext_catalog_name is not null
  18962.     begin
  18963.         select @ftcatid = ftcatid from sysfulltextcatalogs where name = @fulltext_catalog_name
  18964.         if @ftcatid is null
  18965.         begin
  18966.             raiserror(7641,-1,-1,@fulltext_catalog_name)
  18967.             return 1
  18968.         end
  18969.     end
  18970.  
  18971.     if @table_name is not null
  18972.     begin
  18973.         -- VALIDATE TABLE NAME --
  18974.         --    (1) Must exist in current database
  18975.         declare @objid int
  18976.         select @objid = object_id(@table_name, 'local')
  18977.         if @objid is null
  18978.         begin
  18979.             declare @curdbname sysname
  18980.             select @curdbname = db_name()
  18981.             raiserror(15009,-1,-1 ,@table_name, @curdbname)
  18982.             return 1
  18983.         end
  18984.         --    (2) Must be a user table (and not a temp table)
  18985.         if ObjectProperty(@objid, 'IsUserTable') = 0 OR substring(parsename(@table_name,1),1,1) = '#'
  18986.         begin
  18987.             raiserror(15218,-1,-1 ,@table_name)
  18988.             return 1
  18989.         end
  18990.     end
  18991.  
  18992.     select susr.name as TABLE_OWNER, sobj.name as TABLE_NAME,
  18993.         sdex.name as FULLTEXT_KEY_INDEX_NAME,
  18994.         ObjectProperty(sobj.id, 'TableFulltextKeyColumn') as FULLTEXT_KEY_COLID,
  18995.         ObjectProperty(sobj.id, 'TableHasActiveFulltextIndex') as FULLTEXT_INDEX_ACTIVE,
  18996.         scat.name as FULLTEXT_CATALOG_NAME
  18997.         from sysobjects as sobj, sysindexes as sdex, sysusers as susr, sysfulltextcatalogs as scat
  18998.         where(
  18999.                 @fulltext_catalog_name is null or
  19000.                 sobj.ftcatid = @ftcatid
  19001.              ) and
  19002.              (
  19003.                 @table_name is null or
  19004.                 sobj.id = @objid
  19005.              ) and
  19006.               sobj.uid = susr.uid and
  19007.               sobj.ftcatid = scat.ftcatid and
  19008.               sdex.status & 33554432 <> 0 and    /* means that this is the index used enforce
  19009.                                                    the uniqueness of the full-text key column */
  19010.               sdex.id = sobj.id
  19011.         order by TABLE_OWNER, TABLE_NAME
  19012.  
  19013.     -- SUCCESS --
  19014.     return 0    -- sp_help_fulltext_tables
  19015. go
  19016.  
  19017. ---------------------------- sp_help_fulltext_tables_cursor ------------------------------
  19018. raiserror(15339,-1,-1,'sp_help_fulltext_tables_cursor')
  19019. go
  19020. create proc sp_help_fulltext_tables_cursor
  19021.     @cursor_return CURSOR VARYING OUTPUT,
  19022.     @fulltext_catalog_name        sysname = NULL,         -- full-text catalog name
  19023.     @table_name nvarchar(517) = NULL    -- table name
  19024. as
  19025.     -- FULLTEXT MUST BE ACTIVE IN DATABASE --
  19026.     if DatabaseProperty(db_name(), 'IsFulltextEnabled') = 0
  19027.     begin
  19028.         raiserror(15601,-1,-1)
  19029.         return 1
  19030.     end
  19031.  
  19032.     -- CATALOG MUST EXIST IF SPECIFIED --
  19033.     declare @ftcatid smallint
  19034.     if @fulltext_catalog_name is not null
  19035.     begin
  19036.         select @ftcatid = ftcatid from sysfulltextcatalogs where name = @fulltext_catalog_name
  19037.         if @ftcatid is null
  19038.         begin
  19039.             raiserror(7641,-1,-1,@fulltext_catalog_name)
  19040.             return 1
  19041.         end
  19042.     end
  19043.  
  19044.     if @table_name is not null
  19045.     begin
  19046.         -- VALIDATE TABLE NAME --
  19047.         --    (1) Must exist in current database
  19048.         declare @objid int
  19049.         select @objid = object_id(@table_name, 'local')
  19050.         if @objid is null
  19051.         begin
  19052.             declare @curdbname sysname
  19053.             select @curdbname = db_name()
  19054.             raiserror(15009,-1,-1 ,@table_name, @curdbname)
  19055.             return 1
  19056.         end
  19057.         --    (2) Must be a user table (and not a temp table)
  19058.         if ObjectProperty(@objid, 'IsUserTable') = 0
  19059.                          OR substring(parsename(@table_name,1),1,1) = '#'
  19060.         begin
  19061.             raiserror(15218,-1,-1 ,@table_name)
  19062.             return 1
  19063.         end
  19064.     end
  19065.  
  19066.     set @cursor_return =    CURSOR LOCAL SCROLL DYNAMIC FOR
  19067.     select susr.name as TABLE_OWNER, sobj.name as TABLE_NAME,
  19068.         sdex.name as FULLTEXT_KEY_INDEX_NAME,
  19069.         ObjectProperty(sobj.id, 'TableFulltextKeyColumn') as FULLTEXT_KEY_COLID,
  19070.         ObjectProperty(sobj.id, 'TableHasActiveFulltextIndex') as FULLTEXT_INDEX_ACTIVE,
  19071.         scat.name as FULLTEXT_CATALOG_NAME
  19072.         from sysobjects as sobj, sysindexes as sdex, sysusers as susr, sysfulltextcatalogs as scat
  19073.         where(
  19074.                 @fulltext_catalog_name is null or
  19075.                 sobj.ftcatid = @ftcatid
  19076.              ) and
  19077.              (
  19078.                 @table_name is null or
  19079.                 sobj.id = @objid
  19080.              ) and
  19081.               sobj.uid = susr.uid and
  19082.               sobj.ftcatid = scat.ftcatid and
  19083.               sdex.status & 33554432 <> 0 and    /* means that this is the index used enforce
  19084.                                                    the uniqueness of the full-text key column */
  19085.               sdex.id = sobj.id
  19086.         order by TABLE_OWNER, TABLE_NAME
  19087.  
  19088.     open @cursor_return
  19089.  
  19090.     -- SUCCESS --
  19091.     return 0    -- sp_help_fulltext_tables_cursor
  19092. go
  19093.  
  19094. ---------------------------- sp_help_fulltext_columns ------------------------------
  19095. raiserror(15339,-1,-1,'sp_help_fulltext_columns')
  19096. go
  19097. create proc sp_help_fulltext_columns
  19098.     @table_name nvarchar(517) = NULL,        -- table name
  19099.     @column_name    sysname = NULL            -- column name
  19100. as
  19101.     -- FULLTEXT MUST BE ACTIVE IN DATABASE --
  19102.     if DatabaseProperty(db_name(), 'IsFulltextEnabled') = 0
  19103.     begin
  19104.         raiserror(15601,-1,-1)
  19105.         return 1
  19106.     end
  19107.  
  19108.     if @table_name is not null
  19109.     begin
  19110.         -- VALIDATE TABLE NAME --
  19111.         --    (1) Must exist in current database
  19112.         declare @objid int
  19113.         select @objid = object_id(@table_name, 'local')
  19114.         if @objid is null
  19115.         begin
  19116.             declare @curdbname sysname
  19117.             select @curdbname = db_name()
  19118.             raiserror(15009,-1,-1 ,@table_name, @curdbname)
  19119.             return 1
  19120.         end
  19121.         --    (2) Must be a user table (and not a temp table)
  19122.         if ObjectProperty(@objid, 'IsUserTable') = 0
  19123.                              OR substring(parsename(@table_name,1),1,1) = '#'
  19124.         begin
  19125.             raiserror(15218,-1,-1 ,@table_name)
  19126.             return 1
  19127.         end
  19128.  
  19129.         -- VALIDATE COLUMN NAME (CANNOT BE COMPUTED) --
  19130.         if @column_name is not null
  19131.         begin
  19132.             declare @typename sysname
  19133.             select @typename = type_name(ColumnProperty(@objid, @column_name, 'SystemType'))
  19134.             if @typename is null OR ColumnProperty(@objid, @column_name, 'IsComputed') = 1
  19135.             begin
  19136.                 raiserror(15104,-1,-1,@table_name,@column_name)
  19137.                 return 1
  19138.             end
  19139.         end
  19140.  
  19141.     end
  19142.  
  19143.     select distinct
  19144.         susr.name as TABLE_OWNER,
  19145.         sobj.id as TABLE_ID,
  19146.         sobj.name as TABLE_NAME,
  19147.         scol.name as FULLTEXT_COLUMN_NAME,
  19148.         scol.colid as FULLTEXT_COLID,
  19149.         b.FT_BLOBTPNAME as FULLTEXT_BLOBTP_COLNAME,
  19150.         a.FT_BLOBTPCOLID as FULLTEXT_BLOBTP_COLID,
  19151.         scol.language as FULLTEXT_LANGUAGE
  19152.     from
  19153.         sysobjects as sobj,
  19154.          sysusers as susr,
  19155.         syscolumns as scol
  19156.         left outer join
  19157.             (
  19158.             select     sdep.id            as TABLE_ID,
  19159.                     sdep.number        as FULLTEXT_COLID,
  19160.                     sdep.depnumber    as FT_BLOBTPCOLID
  19161.             from
  19162.                     sysdepends as sdep,
  19163.                     syscolumns as scol
  19164.             where
  19165.                     scol.colid = sdep.number
  19166.                 and scol.id = sdep.id
  19167.                 and sdep.deptype = 1
  19168.                 and ColumnProperty(scol.id, scol.name, 'IsFullTextIndexed') = 1
  19169.             ) as a
  19170.         on (scol.colid = a.FULLTEXT_COLID and scol.id = a.TABLE_ID)
  19171.         left outer join
  19172.             (
  19173.             select     sdep.id            as TABLE_ID,
  19174.                     sdep.depnumber    as FT_BLOBTPCOLID,
  19175.                     scol.name        as FT_BLOBTPNAME,
  19176.                     sdep.number        as FULLTEXT_COLID
  19177.             from
  19178.                     syscolumns as scol,
  19179.                     sysdepends as sdep
  19180.             where
  19181.                     scol.colid = sdep.depnumber
  19182.                 and ColumnProperty(sdep.id, scol.name, 'IsTypeForFullTextBlob') = 1
  19183.             ) as b
  19184.         on (a.FULLTEXT_COLID = b.FULLTEXT_COLID and a.TABLE_ID = b.TABLE_ID)
  19185.     where (
  19186.             @table_name is null or
  19187.             sobj.id = @objid
  19188.           ) and
  19189.           scol.id = sobj.id and
  19190.           sobj.uid = susr.uid and
  19191.           (
  19192.               @column_name is null or
  19193.               scol.name = @column_name
  19194.           ) and
  19195.           ColumnProperty(sobj.id, scol.name, 'IsFullTextIndexed') = 1
  19196.     order by TABLE_OWNER, TABLE_NAME, FULLTEXT_COLID
  19197.  
  19198.     -- SUCCESS --
  19199.     return 0    -- sp_help_fulltext_columns
  19200. go
  19201.  
  19202. ---------------------------- sp_help_fulltext_columns_cursor ------------------------------
  19203. raiserror(15339,-1,-1,'sp_help_fulltext_columns_cursor')
  19204. go
  19205. create proc sp_help_fulltext_columns_cursor
  19206.     @cursor_return CURSOR VARYING OUTPUT,
  19207.     @table_name nvarchar(517) = NULL,        -- table name
  19208.     @column_name    sysname = NULL                -- column name
  19209. as
  19210.     -- FULLTEXT MUST BE ACTIVE IN DATABASE --
  19211.     if DatabaseProperty(db_name(), 'IsFulltextEnabled') = 0
  19212.     begin
  19213.         raiserror(15601,-1,-1)
  19214.         return 1
  19215.     end
  19216.  
  19217.     if @table_name is not null
  19218.     begin
  19219.         -- VALIDATE TABLE NAME --
  19220.         --    (1) Must exist in current database
  19221.         declare @objid int
  19222.         select @objid = object_id(@table_name, 'local')
  19223.         if @objid is null
  19224.         begin
  19225.             declare @curdbname sysname
  19226.             select @curdbname = db_name()
  19227.             raiserror(15009,-1,-1 ,@table_name, @curdbname)
  19228.             return 1
  19229.         end
  19230.         --    (2) Must be a user table (and not a temp table)
  19231.         if ObjectProperty(@objid, 'IsUserTable') = 0
  19232.                                  OR substring(parsename(@table_name,1),1,1) = '#'
  19233.         begin
  19234.             raiserror(15218,-1,-1 ,@table_name)
  19235.             return 1
  19236.         end
  19237.  
  19238.         -- VALIDATE COLUMN NAME (CANNOT BE COMPUTED) --
  19239.         if @column_name is not null
  19240.         begin
  19241.             declare @typename sysname
  19242.             select @typename = type_name(ColumnProperty(@objid, @column_name, 'SystemType'))
  19243.             if @typename is null OR ColumnProperty(@objid, @column_name, 'IsComputed') = 1
  19244.             begin
  19245.                 raiserror(15104,-1,-1,@table_name,@column_name)
  19246.                 return 1
  19247.             end
  19248.         end
  19249.     end
  19250.  
  19251.     set @cursor_return =    CURSOR LOCAL SCROLL DYNAMIC FOR
  19252.         select distinct
  19253.             susr.name as TABLE_OWNER,
  19254.             sobj.id as TABLE_ID,
  19255.             sobj.name as TABLE_NAME,
  19256.             scol.name as FULLTEXT_COLUMN_NAME,
  19257.             scol.colid as FULLTEXT_COLID,
  19258.             b.FT_BLOBTPNAME as FULLTEXT_BLOBTP_COLNAME,
  19259.             a.FT_BLOBTPCOLID as FULLTEXT_BLOBTP_COLID,
  19260.             scol.language as FULLTEXT_LANGUAGE
  19261.         from
  19262.             sysobjects as sobj,
  19263.             sysusers as susr,
  19264.             syscolumns as scol
  19265.             left outer join
  19266.                 (
  19267.                 select     sdep.id            as TABLE_ID,
  19268.                         sdep.number        as FULLTEXT_COLID,
  19269.                         sdep.depnumber    as FT_BLOBTPCOLID
  19270.                 from
  19271.                         sysdepends as sdep,
  19272.                         syscolumns as scol
  19273.                 where
  19274.                         scol.colid = sdep.number
  19275.                     and scol.id = sdep.id
  19276.                     and sdep.deptype = 1
  19277.                     and ColumnProperty(scol.id, scol.name, 'IsFullTextIndexed') = 1
  19278.                 ) as a
  19279.             on (scol.colid = a.FULLTEXT_COLID and scol.id = a.TABLE_ID)
  19280.             left outer join
  19281.                 (
  19282.                 select     sdep.id            as TABLE_ID,
  19283.                         sdep.depnumber    as FT_BLOBTPCOLID,
  19284.                         scol.name        as FT_BLOBTPNAME,
  19285.                         sdep.number        as FULLTEXT_COLID
  19286.                 from
  19287.                         syscolumns as scol,
  19288.                         sysdepends as sdep
  19289.                 where
  19290.                         scol.colid = sdep.depnumber
  19291.                     and ColumnProperty(sdep.id, scol.name, 'IsTypeForFullTextBlob') = 1
  19292.                 ) as b
  19293.             on (a.FULLTEXT_COLID = b.FULLTEXT_COLID and a.TABLE_ID = b.TABLE_ID)
  19294.         where (
  19295.                 @table_name is null or
  19296.                 sobj.id = @objid
  19297.               ) and
  19298.               scol.id = sobj.id and
  19299.               sobj.uid = susr.uid and
  19300.               (
  19301.                   @column_name is null or
  19302.                   scol.name = @column_name
  19303.               ) and
  19304.               ColumnProperty(sobj.id, scol.name, 'IsFullTextIndexed') = 1
  19305.         order by TABLE_OWNER, TABLE_NAME, FULLTEXT_COLID
  19306.  
  19307.     open @cursor_return
  19308.  
  19309.     -- SUCCESS --
  19310.     return 0    -- sp_help_fulltext_columns_cursor
  19311. go
  19312.  
  19313. -- GRANT PUBLIC ACCESS --
  19314. grant execute on sp_fulltext_service to public
  19315. grant execute on sp_fulltext_database to public
  19316. grant execute on sp_fulltext_catalog to public
  19317. grant execute on sp_fulltext_table to public
  19318. grant execute on sp_fulltext_column to public
  19319. grant execute on sp_help_fulltext_catalogs to public
  19320. grant execute on sp_help_fulltext_catalogs_cursor to public
  19321. grant execute on sp_help_fulltext_tables  to public
  19322. grant execute on sp_help_fulltext_tables_cursor  to public
  19323. grant execute on sp_help_fulltext_columns  to public
  19324. grant execute on sp_help_fulltext_columns_cursor  to public
  19325. -- sp_fulltext_getdata is NOT for CUSTOMER USE! (do not doc)
  19326. go
  19327.  
  19328. /*************************  END FULLTEXT INDEXES *****************************/
  19329.  
  19330. checkpoint
  19331. go
  19332.  
  19333. /**********************  SQLTRACE STORED PROCEDURES **************************/
  19334.  
  19335. if object_id('sp_trace_getdata','P') IS NOT NULL
  19336.     drop procedure sp_trace_getdata
  19337. go
  19338.  
  19339. raiserror(15339,-1,-1,'sp_trace_getdata')
  19340. go
  19341. create procedure sp_trace_getdata
  19342.     (@traceid int,
  19343.      @records int = 0
  19344.     )
  19345. as
  19346.  
  19347. select * from OpenRowset(TrcData, @traceid, @records)
  19348. go 
  19349.  
  19350. /*********************** END SQLTRACE PROCEDURES *****************************/
  19351.  
  19352. checkpoint
  19353. go
  19354.  
  19355.  
  19356. if object_id('sp_describe_cursor','P') IS NOT NULL
  19357.     drop procedure sp_describe_cursor
  19358. if object_id('sp_describe_cursor_columns','P') IS NOT NULL
  19359.     drop procedure sp_describe_cursor_columns
  19360. if object_id('sp_describe_cursor_tables','P') IS NOT NULL
  19361.     drop procedure sp_describe_cursor_tables
  19362. if object_id('sp_cursor_list','P') IS NOT NULL
  19363.     drop procedure sp_cursor_list
  19364. go
  19365.  
  19366. raiserror(15339,-1,-1,'sp_describe_cursor')
  19367. go
  19368. -- Creation of sp_describe_cursor
  19369.  
  19370. Create Procedure sp_describe_cursor
  19371. (  @cursor_return CURSOR VARYING OUTPUT,
  19372.    @cursor_source nvarchar (30),
  19373.    @cursor_identity nvarchar (128)
  19374. )
  19375. AS
  19376.  
  19377. declare @scope int
  19378.  
  19379. /* Check if the cursor exists by name or handle. */
  19380. If cursor_status ( @cursor_source, @cursor_identity ) >= -1
  19381. begin
  19382.     if lower(convert(varchar(30), @cursor_source)) = 'local' OR
  19383.         lower(convert(varchar(128), @cursor_source)) = 'variable'
  19384.         select @scope = 1
  19385.     else
  19386.     if lower(convert(varchar(30), @cursor_source)) = 'global'
  19387.         select @scope = 2
  19388.  
  19389.  
  19390.     set @cursor_return =  CURSOR LOCAL SCROLL DYNAMIC FOR
  19391.                     SELECT reference_name, cursor_name, cursor_scope,
  19392.                     status, model, concurrency, scrollable,
  19393.                     open_status, cursor_rows, fetch_status,
  19394.                     column_count, row_count, last_operation,
  19395.                     cursor_handle
  19396.                     FROM master.dbo.syscursorrefs scr, master.dbo.syscursors sc
  19397.                     WHERE     scr.cursor_scope = @scope and
  19398.                       scr.reference_name = @cursor_identity and
  19399.                       scr.cursor_handl = sc.cursor_handle
  19400.                 ORDER BY 3, 1
  19401.                 FOR READ ONLY
  19402.     open @cursor_return
  19403.  
  19404. end
  19405. go
  19406.  
  19407. raiserror(15339,-1,-1,'sp_describe_cursor_columns')
  19408. go
  19409. -- Creation of sp_describe_cursor_columns
  19410.  
  19411. Create Procedure sp_describe_cursor_columns
  19412. (  @cursor_return CURSOR VARYING OUTPUT,
  19413.    @cursor_source nvarchar (30),
  19414.    @cursor_identity nvarchar (128)
  19415. )
  19416. AS
  19417.  
  19418. declare @scope int
  19419.  
  19420. /* Check if the cursor exists by name or handle. */
  19421. If cursor_status ( @cursor_source, @cursor_identity ) >= -1
  19422. begin
  19423.     if lower(convert(varchar(30), @cursor_source)) = 'local' OR
  19424.         lower(convert(varchar(128), @cursor_source)) = 'variable'
  19425.         select @scope = 1
  19426.     else
  19427.     if lower(convert(varchar(30), @cursor_source)) = 'global'
  19428.         select @scope = 2
  19429.  
  19430.     set @cursor_return =      CURSOR LOCAL SCROLL DYNAMIC FOR
  19431.                 SELECT column_name, ordinal_position, column_characteristics_flags,
  19432.                     column_size, data_type_sql, column_precision,
  19433.                     column_scale, order_position, order_direction,
  19434.                     hidden_column, columnid, objectid, dbid, dbname
  19435.                 FROM master.dbo.syscursorrefs scr, master.dbo.syscursorcolumns scc
  19436.                 WHERE     scr.cursor_scope = @scope and
  19437.                     scr.reference_name = @cursor_identity and
  19438.                     scr.cursor_handl = scc.cursor_handle
  19439.                 ORDER BY 2
  19440.                 FOR READ ONLY
  19441.     open @cursor_return
  19442.  
  19443. end
  19444. go
  19445.  
  19446. raiserror(15339,-1,-1,'sp_describe_cursor_tables')
  19447. go
  19448. -- Creation of sp_describe_cursor_tables
  19449.  
  19450. Create Procedure sp_describe_cursor_tables
  19451. (  @cursor_return CURSOR VARYING OUTPUT,
  19452.    @cursor_source nvarchar (30),
  19453.    @cursor_identity nvarchar (128)
  19454. )
  19455. AS
  19456.  
  19457. declare @scope int
  19458.  
  19459. /* Check if the cursor exists by name or handle. */
  19460. If cursor_status ( @cursor_source, @cursor_identity ) >= -1
  19461. begin
  19462.     if lower(convert(varchar(30), @cursor_source)) = 'local' OR
  19463.         lower(convert(varchar(128), @cursor_source)) = 'variable'
  19464.         select @scope = 1
  19465.     else
  19466.     if lower(convert(varchar(30), @cursor_source)) = 'global'
  19467.         select @scope = 2
  19468.  
  19469.     set @cursor_return =      CURSOR LOCAL SCROLL DYNAMIC FOR
  19470.                 SELECT table_owner, table_name, optimizer_hint, lock_type, server_name, objectid, dbid, dbname
  19471.                 FROM master.dbo.syscursorrefs scr, master.dbo.syscursortables sct
  19472.                 WHERE     scr.cursor_scope = @scope and
  19473.                     scr.reference_name = @cursor_identity and
  19474.                     scr.cursor_handl = sct.cursor_handle
  19475.                 FOR READ ONLY
  19476.     open @cursor_return
  19477. end
  19478. go
  19479.  
  19480. raiserror(15339,-1,-1,'sp_cursor_list')
  19481. go
  19482. -- Creation of sp_cursor_list
  19483.  
  19484. create procedure sp_cursor_list
  19485. (
  19486.    @cursor_return CURSOR VARYING OUTPUT,
  19487.    @cursor_scope int
  19488. )
  19489. AS
  19490.  
  19491. if (@cursor_scope < 1) OR (@cursor_scope > 3)
  19492.     begin
  19493.         /* Raise an error: ?The value of parameter  is invalid? */
  19494.         raiserror ( 16902, 1, 1,N'sp_cursor_list', N'@cursor_scope')
  19495.         return (1)
  19496.     end
  19497.  
  19498. if ( @cursor_scope  < 3)
  19499. begin
  19500.     set @cursor_return =  CURSOR LOCAL SCROLL DYNAMIC FOR
  19501.                     SELECT reference_name, cursor_name, cursor_scope,
  19502.                     status, model, concurrency, scrollable,
  19503.                     open_status, cursor_rows, fetch_status,
  19504.                     column_count, row_count, last_operation,
  19505.                     cursor_handle
  19506.                 FROM master.dbo.syscursorrefs scr, master.dbo.syscursors sc
  19507.                 WHERE     scr.cursor_scope = @cursor_scope AND
  19508.                     scr.cursor_handl = sc.cursor_handle
  19509.                 FOR READ ONLY
  19510. end
  19511. else
  19512. begin
  19513.     set @cursor_return =  CURSOR LOCAL SCROLL DYNAMIC FOR
  19514.                     SELECT reference_name, cursor_name, cursor_scope,
  19515.                     status, model, concurrency, scrollable,
  19516.                     open_status, cursor_rows, fetch_status,
  19517.                     column_count, row_count, last_operation,
  19518.                     cursor_handle
  19519.                 FROM master.dbo.syscursorrefs scr, master.dbo.syscursors sc
  19520.                 WHERE scr.cursor_handl = sc.cursor_handle
  19521.                 FOR READ ONLY
  19522. end
  19523. open @cursor_return
  19524. go
  19525.  
  19526. /************************  END-CURSORINFO-STORED-PROCS  ***********************/
  19527.  
  19528. -- GRANT PUBLIC ACCESS --
  19529. grant execute on sp_describe_cursor to public
  19530. grant execute on sp_describe_cursor_columns to public
  19531. grant execute on sp_describe_cursor_tables to public
  19532. grant execute on sp_cursor_list to public
  19533. go
  19534.  
  19535. checkpoint
  19536. go
  19537.  
  19538. print ' '
  19539. print 'Granting privileges on system tables.'
  19540. go
  19541.  
  19542. grant select on syscharsets to public
  19543. grant select on syscolumns to public
  19544. grant select on syscomments to public
  19545. grant select on sysconfigures to public
  19546. grant select on sysdatabases to public
  19547. grant select on sysdepends to public
  19548. grant select on sysdevices to public
  19549. grant select on sysindexes to public
  19550. grant select on syslanguages to public
  19551. go
  19552.  
  19553.  
  19554. checkpoint
  19555. go
  19556.  
  19557. grant select on sysmessages to public
  19558. grant select on sysobjects to public
  19559. grant select on sysprotects to public
  19560. grant select on syspermissions to public
  19561. grant select on syssegments to public
  19562. grant select on sysservers to public
  19563. grant select on systypes to public
  19564. grant select on sysusers to public
  19565. grant select on sysreferences to public
  19566. grant select on sysfiles to public
  19567. grant select on sysfilegroups to public
  19568. grant select on sysfulltextcatalogs to public
  19569. go
  19570.  
  19571. DENY SELECT (providerstring) ON sysservers TO PUBLIC
  19572. go
  19573.  
  19574. checkpoint
  19575. go
  19576.  
  19577. print ' '
  19578. print 'Granting privileges on system stored procedures'
  19579. go
  19580.  
  19581. grant execute on MS_sqlctrs_users to public
  19582. go
  19583.  
  19584. grant execute on sp_user_counter1   to public
  19585. grant execute on sp_user_counter2   to public
  19586. grant execute on sp_user_counter3   to public
  19587. grant execute on sp_user_counter4   to public
  19588. grant execute on sp_user_counter5   to public
  19589. grant execute on sp_user_counter6   to public
  19590. grant execute on sp_user_counter7   to public
  19591. grant execute on sp_user_counter8   to public
  19592. grant execute on sp_user_counter9   to public
  19593. grant execute on sp_user_counter10  to public
  19594.  
  19595. checkpoint
  19596. go
  19597.  
  19598. grant execute on sp_addmessage to public
  19599. grant execute on sp_addumpdevice to public
  19600. grant execute on sp_addtype to public
  19601. grant execute on sp_altermessage to public
  19602. grant execute on sp_bindefault to public
  19603. grant execute on sp_bindrule to public
  19604. grant execute on sp_checknames to public
  19605. grant execute on sp_configure to public
  19606. grant execute on sp_cursor to public
  19607. grant execute on sp_cursorclose to public
  19608. grant execute on sp_cursorfetch to public
  19609. grant execute on sp_cursoropen to public
  19610. grant execute on sp_cursoroption to public
  19611. grant execute on sp_dboption to public
  19612. grant execute on sp_bindsession to public
  19613. grant execute on sp_getbindtoken to public
  19614. grant execute on sp_dbcmptlevel to public
  19615. grant execute on sp_executesql to public
  19616. grant execute on sp_prepare to public
  19617. grant execute on sp_execute to public
  19618. grant execute on sp_prepexec to public
  19619. grant execute on sp_prepexecrpc to public
  19620. grant execute on sp_unprepare to public
  19621. grant execute on sp_cursorprepare to public
  19622. grant execute on sp_cursorexecute to public
  19623. grant execute on sp_cursorprepexec to public
  19624. grant execute on sp_cursorunprepare to public
  19625. grant execute on sp_createorphan to public
  19626. grant execute on sp_droporphans to public
  19627. grant execute on sp_reset_connection to public
  19628. grant execute on sp_getschemalock to public
  19629. grant execute on sp_releaseschemalock to public
  19630. grant execute on sp_xml_preparedocument to public
  19631. grant execute on sp_xml_removedocument to public
  19632. go
  19633.  
  19634. checkpoint
  19635. go
  19636. grant execute on sp_diskdefault to public
  19637. grant execute on sp_dropdevice to public
  19638.  
  19639. grant execute on sp_depends to public
  19640. grant execute on sp_dropmessage to public
  19641. grant execute on sp_droptype to public
  19642. go
  19643. grant execute on sp_help to public
  19644. grant execute on sp_helpconstraint to public
  19645. grant execute on sp_helpdb to public
  19646. grant execute on sp_helpfile to public
  19647. grant execute on sp_helpfilegroup to public
  19648. grant execute on sp_helpdevice to public
  19649. grant execute on sp_helpextendedproc to public
  19650. grant execute on sp_helpgroup to public
  19651. grant execute on sp_helpindex to public
  19652. grant execute on sp_helpstats to public
  19653. grant execute on sp_helplanguage to public
  19654. grant execute on sp_helplog to public
  19655. grant execute on sp_helplogins to public
  19656. grant execute on sp_helpremotelogin to public
  19657. grant execute on sp_helprotect to public
  19658. grant execute on sp_helpsort to public
  19659. grant execute on sp_helpsql to public
  19660. grant execute on sp_helptext to public
  19661. grant execute on sp_helpuser to public
  19662. grant execute on sp_lock to public
  19663. grant execute on sp_getapplock to public
  19664. grant execute on sp_releaseapplock to public
  19665. grant select on system_function_schema.fn_helpcollations to public
  19666. grant select on system_function_schema.fn_servershareddrives to public
  19667. grant select on system_function_schema.fn_virtualfilestats to public
  19668. grant select on system_function_schema.fn_virtualservernodes to public
  19669.  
  19670. go
  19671.  
  19672. checkpoint
  19673. go
  19674.  
  19675. grant execute on sp_objectfilegroup to public
  19676. grant execute on sp_procoption to public
  19677. grant execute on sp_recompile to public
  19678. grant execute on sp_remoteoption to public
  19679. grant execute on sp_rename to public
  19680. grant execute on sp_renamedb to public
  19681. grant execute on sp_spaceused to public
  19682. grant execute on sp_sqlexec to public
  19683. go
  19684.  
  19685. grant execute on sp_blockcnt to public
  19686. grant execute on sp_tableoption to public
  19687. grant execute on sp_invalidate_textptr to public
  19688. grant execute on sp_indexoption to public
  19689. grant execute on sp_tempdbspace to public
  19690. go
  19691.  
  19692. grant execute on sp_unbindefault to public
  19693. grant execute on sp_unbindrule to public
  19694. grant execute on sp_validname to public
  19695. grant execute on sp_validlang to public
  19696. grant execute on sp_who to public
  19697. grant execute on sp_who2 to public
  19698. grant execute on sp_updatestats to public
  19699. grant execute on sp_createstats to public
  19700. grant execute on sp_autostats to public
  19701. grant execute on sp_helptrigger to public
  19702. grant execute on sp_addextendedproperty to public
  19703. grant execute on sp_updateextendedproperty to public
  19704. grant execute on sp_dropextendedproperty to public
  19705. grant execute on sp_addremotelogin to public
  19706. grant execute on sp_dropremotelogin to public
  19707. go
  19708.  
  19709. --grant select on system function
  19710. grant select on system_function_schema.fn_listextendedproperty to public
  19711. go
  19712.  
  19713. -- grant access to access resync query sps
  19714. grant execute on sp_resyncprepare to public
  19715. grant execute on sp_resyncexecute to public
  19716. grant execute on sp_resyncexecutesql to public
  19717. grant execute on sp_resyncuniquetable to public
  19718.  
  19719. checkpoint
  19720. go
  19721.  
  19722. print ' '
  19723. print 'Granting privileges on extended stored procedures'
  19724. go
  19725.  
  19726. grant execute on xp_sprintf to public
  19727. grant execute on xp_sscanf to public
  19728. grant execute on xp_msver to public
  19729. go
  19730.  
  19731. print ' '
  19732. print 'Granting privileges on objects in model database.'
  19733. go
  19734. use model
  19735. go
  19736. grant select on sysconstraints to public
  19737. grant select on syscolumns to public
  19738. grant select on syscomments to public
  19739. grant select on sysdepends to public
  19740. grant select on sysindexes to public
  19741. grant select on sysobjects to public
  19742. grant select on sysprotects to public
  19743. grant select on syspermissions to public
  19744. grant select on syssegments to public
  19745. grant select on systypes to public
  19746. grant select on sysusers to public
  19747. grant select on sysreferences to public
  19748. grant select on sysfiles to public
  19749. grant select on sysfilegroups to public
  19750. grant select on sysfulltextcatalogs to public
  19751. go
  19752.  
  19753. use master
  19754. go
  19755.  
  19756. checkpoint
  19757. go
  19758.  
  19759. /*
  19760. ** Set some things now that sp_configure has been created.
  19761. */
  19762. print ' '
  19763. print 'Making final database configuration settings.'
  19764. go
  19765.  
  19766. print 'Forcing config for remote access to 1'
  19767. exec sp_configure 'remote access',1
  19768. go
  19769.  
  19770. exec sp_MS_upd_sysobj_category 2  --Now do catalog updates.
  19771.  
  19772. go
  19773.  
  19774. --- Enable auto-create and update of statistics
  19775. exec sp_dboption 'tempdb', 'auto create statistics', 'on'
  19776. exec sp_dboption 'master', 'auto create statistics', 'on'
  19777. exec sp_dboption 'model', 'auto create statistics', 'on'
  19778. go
  19779. exec sp_dboption 'tempdb', 'auto update statistics', 'on'
  19780. exec sp_dboption 'master', 'auto update statistics', 'on'
  19781. exec sp_dboption 'model', 'auto update statistics', 'on'
  19782. go
  19783. exec sp_dboption 'master', 'torn page detection', 'on'
  19784. exec sp_dboption 'model', 'torn page detection', 'on'
  19785. go
  19786.  
  19787. exec sp_dboption 'master','trunc. log on chkpt.','true'
  19788. go
  19789. exec sp_configure 'allow updates',0
  19790. reconfigure with override
  19791.  
  19792. print ' '
  19793. -- print 'Checking objects created by ProcSyst.SQL ....'
  19794. go
  19795.  
  19796. declare @vdt varchar(99)
  19797. select  @vdt = convert(varchar,getdate(),113)
  19798. raiserror('Finishing Install\ProcSyst.SQL at  %s',0,1,@vdt)
  19799. go
  19800.  
  19801. checkpoint
  19802. go
  19803. -- - -----
  19804.  
  19805. -- test
  19806. -- junk
  19807.